Access over 20 million homework & study documents

Ocaml programming

Content type
User Generated
Rating
Showing Page:
1/19

Sign up to view the full document!

lock_open Sign Up
Showing Page:
2/19

Sign up to view the full document!

lock_open Sign Up
Showing Page:
3/19

Sign up to view the full document!

lock_open Sign Up
End of Preview - Want to read all 19 pages?
Access Now
Unformatted Attachment Preview
OCAML PROGRAMMING Remove sequen4al duplicates # let rec destu>er list = match list with | [] -> [] | [hd] -> [hd] | hd :: hd' :: tl -> if hd = hd' then destu>er (hd' :: tl) else hd :: destu>er (hd' :: tl) ;; val destu>er : 'a list -> 'a list = Remove sequen4al duplicates # let rec destu>er list = match list with | [] -> [] | [hd] -> [hd] [hd] -> [hd] allocates a new list element | hd :: hd' :: tl -> if hd = hd' then destu>er (hd' :: tl) else hd :: destu>er (hd' :: tl) ;; val destu>er : 'a list -> 'a list = More Efficient Solu4on # let rec destu>er = func4on | [] as l -> l | [_] as l -> l | hd :: (hd' :: _ as tl) -> if hd = hd' then destu>er tl else hd :: destu>er tl ;; val destu>er : 'a list -> 'a list = The as pa5ern allowws us to declare a name for the thing matched by a pa5ern or subpa5ern. Even More Efficient # let rec destu>er = func4on | [] | [_] as l -> l | hd :: (hd' :: _ as tl) when hd = hd' -> destu>er tl | hd :: tl -> hd :: destu>er tl ;; val destu>er : 'a list -> 'a list = Ex1 • Find out whether a list is a palindrome • # is_palindrome [ "x" ; "a" ; "m" ; "a" ; "x" ];; - : bool = true • # not (is_palindrome [ "a" ; "b" ]);; - : bool = true Solu4on # let rev list = let rec aux acc = func4on | [] -> acc | h::t -> aux (h::acc) t in aux [] list;; val rev : 'a list -> 'a list = let is_palindrome list = list = rev list;; Ex2 • Insert an element at a cartain posi4on. • # insert_at "alfa" 1 ["a";"b";"c";"d"];; - : st ...
Purchase document to see full attachment
User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.

Anonymous
I was having a hard time with this subject, and this was a great help.

Studypool
4.7
Trustpilot
4.5
Sitejabber
4.4