Question: Functional programming in Ocaml help needed! given the following code and complete what the comment says. ---------------------------------------------------------------------------------------- type 'a str = Cons of 'a *

Functional programming in Ocaml help needed!

given the following code and complete what the comment says.

----------------------------------------------------------------------------------------

type 'a str = Cons of 'a * ('a stream) and 'a stream = unit -> 'a str

let head (s: 'a stream) = let Cons(a, _) = s() in a let tail (s: 'a stream) = let Cons(_, tl)= s() in tl

let rec take (n:int) (s: 'a stream) : 'a list = if n>0 then (head s) :: (take (n-1) (tail s)) else []

let rec map (f: 'a -> 'b) (s:'a stream) : 'b stream = fun () -> Cons (f (head s), map f (tail s)) let rec zip f s1 s2 () = Cons (f (head s1) (head s2), zip f (tail s1) (tail s2))

let rec filter (s: 'a stream) (p: 'a -> bool) : 'a stream = if p (head s) then fun () -> Cons (head s, filter (tail s) p) else (filter (tail s) p)

let rec sieve (s: int stream) : int stream = fun () -> Cons(head s, sieve (filter (tail s) (fun x -> x mod (head s) <> 0)))

let rec nats (i: int) : int stream = fun () -> Cons (i, nats (i+1))

let primes : int stream = sieve (nats 2)

let even x= (x mod 2) = 0 let odd x= (x mod 2) = 1

let rec fibs () = Cons (0,fun () -> Cons(1, zip (+) fibs (tail fibs))) let rec ones = fun () -> Cons (1, ones) let rec zeros = fun () -> Cons (0, zeros)

(* define a function write_list_int: string -> int list -> unit * that takes the name of a file, a list of integers and writes * all the elements of the list in the file, from left to right, * one per line, and then returns unit. * Remember to close any possible channel before ending. *)

(* define a function read_list_int_rev: string -> int list * that takes the name of a text file (which contains one integer per line) * and returns a list of all the integers in reversed order. That is * if the file looks like this: * 1 * 2 * 3 * the returned list has to be [3;2;1] . * Finally, remember to close any input channel before ending. *)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!