Advertisement
karol_dziachan

SimpleTask__Ocaml__

Oct 7th, 2020
3,048
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.74 KB | None | 0 0
  1. (*Karol Dziachan*)
  2.  
  3. (*task 1 - create the function, which the list of lists is flattened by one level*)
  4.  
  5. let rec flatten list=
  6.    List.hd list @  List.hd (List.tl list);;
  7.      
  8.  
  9. flatten[[1;2;3];[4;5;6]] = [1;2;3;4;5;6];;
  10. flatten[[];[1;2;3]] = [1;2;3];;
  11. flatten[[4;5;6];[]] = [4;5;6];;
  12. flatten[[];[]] = [];;
  13.  
  14. (* task 2*)
  15.  
  16. let rec count (x,xs) =
  17.     if xs == [] then failwith ("empty list")
  18.       else if List.tl xs ==  [] then 1
  19.          else if List.hd xs == x then 1+count(x, List.tl xs)
  20.     else count(x , List.tl xs);;
  21.  
  22. count('a', ['a';'l';'a']) = 2;;
  23. count('a', ['a';'l';'a';'a';'m';'a'])= 4;;
  24. count(1, [1;2;3;1;3;1;5;3;1]) = 4;;
  25. count('a', []);;
  26.  
  27. (* task3 *)
  28.  
  29. let rec replicate (x, n) =
  30.   if(n==1) then x
  31.      else if(n==0) then failwith ("nothing")
  32.   else x @ replicate(x, n-1);;
  33.  
  34. replicate(["la"], 3);;
  35. replicate([""], 3);;
  36. replicate(["la"], 0);;
  37. replicate([""], 0);;
  38.  
  39. (*task 4*)
  40.  
  41. let rec sqrtList xs =
  42.   if xs==[] then failwith ("nothing")
  43.      else if List.tl xs != [] then  (List.hd xs)*(List.hd xs) :: (sqrtList(List.tl xs))
  44.   else   List.tl xs @ ([(List.hd xs)*(List.hd xs)]);;
  45.  
  46. sqrtList[1;2;3;(-4)];;
  47.  
  48. (* task 5 *)
  49.  
  50. let rec palindrome xs =
  51.   if xs == [] then failwith ("empty list")
  52.    else
  53.      xs=(List.rev xs);;
  54.  
  55.  
  56.   palindrome["a";"l";"a"];;
  57.   palindrome["k";"a";"j";"a";"k"];;
  58.   palindrome["k";"a";"r";"o";"l"];;
  59.   palindrome["A";"l";"a"];;
  60.   palindrome[];;
  61.  
  62.   (*task 6*)
  63.  
  64.  let rec listLength xs=
  65.             if(xs == []) then failwith ("empty lity")
  66.             else if (List.tl xs != []) then 1+listLength(List.tl xs)
  67.             else 1;;
  68.  
  69.  
  70.    listLength[1;2;3;4;5];;
  71.    listLength["k";"a";"r";"o";"l"];;
  72.    listLength["mother"];;
  73.    listLength["mother"; "father"];;
  74.    listLength[];;
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement