Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (* Return the last element *)
- fun last_element([]) = 0
- | last_element(X::Y) = if Y=[] then X else last_element(Y);
- last_element([3,4,5,1,2,99]);
- (* Return the k'th element *)
- fun kth_element([], k) = 0
- | kth_element(x::X, k) = if k=0 then x else kth_element(X, k-1);
- kth_element([4,2,4,99,1,2], 3);
- (* Reverse a list *)
- fun reverse([]) = []
- | reverse(x::X) = reverse(X) @ [x];
- reverse([1,2,3,4,5,6,7]);
- (* Palindrome *)
- fun palindrome(X) = if X=reverse(X) then true else false;
- palindrome([1,2,3,2,1]);
- palindrome([1,2,3,4,5]);
- (* Flatten a nested list *)
- fun flatten([]) = []
- | flatten(x::X) = x @ flatten(X);
- flatten([[1], [2, 3, 4, 5]]);
- (* Eliminate consecutive duplicates *)
- fun elim_duplicates([]) = []
- | elim_duplicates(x::[]) = [x]
- | elim_duplicates(x::X) = if x=hd(X) then elim_duplicates(X)
- else x::elim_duplicates(X);
- elim_duplicates([1,1,1,1,2,3,3,3,1,3,3,5,5,5,3]);
- (* Pack consecutive duplicates *)
- (* NOT WORKING *)
- fun pack_duplicates([]) = []
- | pack_duplicates(x::[]) = [x]
- | pack_duplicates(x::X) = if x=hd(X) then [x] else X;
- pack_duplicates([1,1,1,1,2,3,3,3,1,3,3,5,5,5,3]);
- (* Run length encoding *)
- (* Can use pack_duplicate(), then get the char of each array and the length *)
- (* Run length decoding *)
- fun create_run(n, char) = if n=0 then [] else char::create_run(n-1, char);
- create_run(4, 9);
- fun decode_run([]) = []
- | decode_run(x::X) = create_run(hd(x), hd(tl(x))) @ decode_run(X);
- decode_run([[4,9],[1,8],[5,7]]);
- (* Create a list of integers within a given range *)
- fun range(a, b) = if a > b then [] else a::range(a+1, b);
- range(4, 9);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement