Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %some exercises (not all are from the book, And I had not done the last one from the book)
- %compress
- compress([], []).
- compress([X], [X]).
- compress([X, X|Tail], Result) :-
- compress([X|Tail], Result).
- compress([X, Y|Tail], [X|Result]) :-
- compress([Y|Tail], Result).
- %size of list
- sizeOfList([],0).
- sizeOfList([Head|Tail], N) :-
- sizeOfList(Tail, N1), N is N1 + 1.
- %element at position
- elementAt(0, [Head|_], Head).
- elementAt(Pos, [_|Tail], Res) :-
- Pos1 is Pos - 1,
- elementAt(Pos1, Tail, Res).
- %last number of list
- lastNumber([List], List). %[List] is a list with just one element
- lastNumber([_|Tail], N) :- lastNumber(Tail, N). % should ignore Head at the begining
- %flatten list (example below)
- %my_flatten([a, [b, [c, d], e]], X).
- %X = [a, b, c, d, e]
- myFlatten(Element,[Element]) :- \+ is_list(Element).
- myFlatten([], []).
- myFlatten([Head|Tail], Result) :-
- myFlatten(Head, Result1), myFlatten(Tail, Result2), append(Result1, Result2, Result).
- %reverse a list
- reverseList(List, Reversed) :-
- reverseList(List, [], Reversed).
- reverseList([], Reversed, Reversed).
- reverseList([Head|Tail], TheOther, Reversed) :-
- reverseList(Tail, [Head|TheOther], Reversed).
- %after 2 days, a new method to reverse a list
- reverseList([Element], [Element]).
- reverseList([Head|Tail], Result) :-
- reverseList(Tail, Result1), append(Result1, [Head], Result).
- %smallest in list
- smallest([TheSmall], TheSmall).
- smallest([Head|Tail], Res) :-
- smallest(Tail, Res1), Head > Res1 -> Res is Res1; Res is Head. % or ... smallest(Tail, Res1), Res is min(Head, Res1).
- %sum list
- sumList([],0).
- sumList([Head|Tail], N) :-
- sumList(Tail, N1), N is N1 + Head.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement