Advertisement
Night_Wood

SML Practice Problems

Feb 27th, 2018
3,074
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (* Return the last element *)
  2. fun last_element([]) = 0
  3.     | last_element(X::Y) = if Y=[] then X else last_element(Y);
  4.  
  5. last_element([3,4,5,1,2,99]);
  6.  
  7. (* Return the k'th element *)
  8. fun kth_element([], k) = 0
  9.     | kth_element(x::X, k) = if k=0 then x else kth_element(X, k-1);
  10.  
  11. kth_element([4,2,4,99,1,2], 3);
  12.  
  13. (* Reverse a list *)
  14. fun reverse([]) = []
  15.     | reverse(x::X) = reverse(X) @ [x];
  16.  
  17. reverse([1,2,3,4,5,6,7]);
  18.  
  19. (* Palindrome *)
  20. fun palindrome(X) = if X=reverse(X) then true else false;
  21.  
  22. palindrome([1,2,3,2,1]);
  23. palindrome([1,2,3,4,5]);
  24.  
  25. (* Flatten a nested list *)
  26. fun flatten([]) = []
  27.     | flatten(x::X) = x @ flatten(X);
  28.  
  29. flatten([[1], [2, 3, 4, 5]]);
  30.  
  31. (* Eliminate consecutive duplicates *)
  32. fun elim_duplicates([]) = []
  33.     | elim_duplicates(x::[]) = [x]
  34.     | elim_duplicates(x::X) = if x=hd(X) then elim_duplicates(X)
  35.         else x::elim_duplicates(X);
  36.  
  37. elim_duplicates([1,1,1,1,2,3,3,3,1,3,3,5,5,5,3]);
  38.  
  39. (* Pack consecutive duplicates *)
  40. (* NOT WORKING *)
  41. fun pack_duplicates([]) = []
  42.     | pack_duplicates(x::[]) = [x]
  43.     | pack_duplicates(x::X) = if x=hd(X) then [x] else X;
  44.  
  45. pack_duplicates([1,1,1,1,2,3,3,3,1,3,3,5,5,5,3]);
  46.  
  47. (* Run length encoding *)
  48. (* Can use pack_duplicate(), then get the char of each array and the length *)
  49.  
  50. (* Run length decoding *)
  51. fun create_run(n, char) = if n=0 then [] else char::create_run(n-1, char);
  52.  
  53. create_run(4, 9);
  54.  
  55. fun decode_run([]) = []
  56.     | decode_run(x::X) = create_run(hd(x), hd(tl(x))) @ decode_run(X);
  57.  
  58. decode_run([[4,9],[1,8],[5,7]]);
  59.  
  60. (* Create a list of integers within a given range *)
  61. fun range(a, b) = if a > b then [] else a::range(a+1, b);
  62.  
  63. range(4, 9);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement