Applying Logical Knowledge

  List Utilities


member(X,[X|_]).
member(X,[_|Y]) :- member(X,Y).

append([], X, X).
append([A|X], Y, [A|Z]) :- append(X, Y, Z).

Exercises:

write_list(+L) - writes the elements

length(+L,-N) - returns the length (use helper length3(L,0,N) that uses accumulator)

sum(+L, -SUM) - sums a list of numbers

reverse(+L1, -L2) - reverses a list (use a helper predicate that has an accumulator, reverse3(+L1, [], -L2))

insert(+X, +L1, -L2) - inserts an element in a sorted list. Use @> and @< to compare elements in sort order.

delete(+X, +L1, -L2) - finds and deletes the element X from L1, returning L2 without the element. (it can succeed or fail if the element isn't there)

nth(+N, +L, -X) - returns the Nth element in a list.

random_elem(+L1, -X, -L2) - removes a random element from a list, returning what's left. good for dealing a deck of cards. There is an arithmetic atom, random, that has a random value between 0.0 and 1.0. Use it with the length of the list: ..., length(L1, LEN), N is 1 + integer(random * LEN), ...

remove_dups(+L1, -L2) - L2 is L1 without any duplicate elements.

split(+L1, A, -L2, -L3) - splits L1 at element A into two parts, L2 & L3 with A in the second part.

shuffle(+L1, -L2) - randomly shuffles the elements of a list.

flatten(+L1, -L2) - takes a list with embedded lists and flattens it to just a list of elements:
?- flatten([ [a,b, [c, d], e], f, [g, h] ], X).
X = [a,b,c,d,e,f,g,h].

A set can be modeled as a sorted list with no duplicates.

union(+S1, +S2, -S3) - S3 is the union of S1 and S2.

intersection(+S1, +S2, S3) - S3 is the intersection of S1 and S2.


Copyright ©2005 Amzi! inc.