% matches Lst with a list containing all numbers between 2 and 7 % % for example, twoSeven( X ) gives X = [2,3,4,5,6,7]. % twoSeven( Lst ) :- bagof( X, for( X, 2, 7 ), Lst ). % matches Lst with a list containing all even numbers between Lo and Hi % % for example, evenRange( 2, 7, X ) gives X = [2,4,6]. % evenRange( Lo, Hi, Lst ) :- bagof( X, (for( X, Lo, Hi ), 0 is X mod 2), Lst ). % compare bagof() and setof(): % list1( Lst ) :- bagof( X, member( X, [1, 2, 2, 3] ), Lst ). list2( Lst ) :- setof( X, member( X, [1, 2, 2, 3] ), Lst ). % quicksort; returns the elements of the A list in sorted order % % question: why do we use findall() and not bagof()? % Hint: try bagof( X, (member( X, [1,2] ), X > 3), Lst ). % and findall( X, (member( X, [1,2] ), X > 3), Lst ). % qsort( [], [] ). qsort( [A|As], Res ) :- findall( Lo, (member( Lo, As ), Lo =< A), Los1 ), qsort( Los1, Los ), findall( Hi, (member( Hi, As ), Hi > A), His1 ), qsort( His1, His ), append( Los, [A|His], Res ). % maps each A element to a B element via Fn % % for example, map( lower_upper, ['a','b','c'], X ) gives X = ['A','B','C']. % % question: if char_code( 'a', X ) gives X = 97, then what do you think % map( char_code, X, "abc" ) gives? % map( _, [], [] ) :- !. map( Fn, [A|As], [B|Bs] ) :- X =.. [Fn, A, B], call( X ), map( Fn, As, Bs ). % prints out the string to the screen % put_str( [] ) :- nl. put_str( [C|[]] ) :- !, put_char( C ). put_str( [C|Cs] ) :- put_char( C ), put_str( Cs ). % prints out the quoted string to the screen % put_codes( [] ) :- nl. put_codes( [C|[]] ) :- !, put_code( C ). put_codes( [C|Cs] ) :- put_code( C ), put_codes( Cs ). % matches Res with the larger of A and B max( A, B, Res ) :- ( A >= B -> Res = A ; Res = B ). % folds the function Fn with terminator T over the A list, matching Res % to the result % foldr( Fn, [A|[]], T, Res ) :- !, X =.. [Fn, A, T, Res], call( X ). foldr( Fn, [A|As], T, Res ) :- foldr( Fn, As, T, Next ), X =.. [Fn, A, Next, Res], call( X ). % matches Max with the maximum element in the A list % maxlist( [A|As], Max ) :- foldr( max, [A|As], A, Max ).