program amb; sets := unstr('[{the that a} {frog elephant thing} {walked treaded grows} {slowly quickly}]'); print(amb(sets)); proc amb(sets); return amb1([], {}, sets); end proc; proc amb1(prev, mbLast, sets); if sets = [] then return prev; else words fromb sets; if exists word in words | (forall last in mbLast | last(#last) = word(1)) and (exists sentence in {amb1(prev with word, {word}, sets)} | true) then return sentence; end if; end if; end proc; end program;