Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. // #############################################
  2. // Hand-in 02.3 – List functions
  3. let rec pclElementAt ls n =
  4. match n, ls with
  5. | _, [] -> 0
  6. | 1, (h::tl) -> h
  7. | _, (h::tl) -> pclElementAt tl (n-1)
  8.  
  9. //> pclElementAt [2; 4; 6; 8; 10] 2;;
  10. //val it : int = 4
  11.  
  12.  
  13.  
  14. // #############################################
  15. // Hand-in 02.4 – List functions
  16. // a.
  17. let rec pclReverse ls =
  18. match ls with
  19. | [] -> []
  20. | (h::tl) -> pclReverse tl @ [h]
  21.  
  22. //> pclReverse [2; 4; 6; 8; 10];;
  23. //val it : int list = [10; 8; 6; 4; 2]
  24.  
  25. // b.
  26. let isPalindrome ls =
  27. if ls = pclReverse ls then true
  28. else false
  29.  
  30. //> isPalindrome [1;2;3;2;2];;
  31. //val it : bool = false
  32. //> isPalindrome [1;2;3;2;1];;
  33. //val it : bool = true
  34.  
  35.  
  36.  
  37. // #############################################
  38. // Hand-in 02.5 – List functions
  39. let rec pclZipper a b =
  40. match a, b with
  41. | [], [] -> []
  42. | (aH::aTl), (bH::bTl) -> if (a.Length = b.Length) then (aH, bH) :: pclZipper aTl bTl else failwith "Lists are different length"
  43. //> pclZipper [1;2;3;4] ['a';'b';'c';'d'];;
  44. //val it : (int * char) list = [(1, 'a'); (2, 'b'); (3, 'c'); (4, 'd')]
  45.  
  46. // if length is not the same, using Options
  47. let rec pclZipperDiffLength a b =
  48. match a, b with
  49. | [], [] -> []
  50. | _, [] -> (Some a.Head, None) :: pclZipperDiffLength a.Tail []
  51. | [], _ -> (None, Some b.Head) :: pclZipperDiffLength [] b.Tail
  52. | (aH::aTl), (bH::bTl) -> (Some aH, Some bH) :: pclZipperDiffLength aTl bTl
  53. //> pclZipperDiffLength [1;2;3;4] ['a';'b';'c';'d';'e';'f'];;
  54. //val it : (int option * char option) list =
  55. // [(Some 1, Some 'a'); (Some 2, Some 'b'); (Some 3, Some 'c');
  56. // (Some 4, Some 'd'); (null, Some 'e'); (null, Some 'f')]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement