Question: Given the following code in Ocmal, Complete what the coment says. /----------------------------------------------------------------------------------------------/ type 'a str = Cons of 'a * ('a stream) and 'a stream
Given the following code in Ocmal, Complete what the coment 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 evens: int stream * as the stream of all even natural * numbers *)
(* define odds: int stream * as the stream of all odd natural * numbers *)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
