Monday 15 September 2014

ocaml - The trick for doing Stream -



ocaml - The trick for doing Stream -

i trying understand stream. concept not complicated. list, tail part thunk instead of concrete sub list.

i can write stream this:

class="lang-ml prettyprint-override">type 'a stream_t = nil | cons of 'a * (unit -> 'a stream_t) allow hd = function | nil -> failwith "hd" | cons (v, _) -> v allow tl = function | nil -> failwith "tl" | cons (_, g) -> g() allow rec take n = function | nil -> [] | cons (_, _) when n = 0 -> [] | cons (hd, g) -> hd::take (n-1) (g()) allow rec filter f = function | nil -> nil | cons (hd, g) -> if f hd cons (hd, fun() -> filter f (g())) else filter f (g())

so far , can write simple stream:

class="lang-ml prettyprint-override">let rec = cons (i, fun() -> (i+1))

now, if asked primes stream, sense difficult. want utilize sieve algorithm. without thinking of stream, can easily. stream, can't do.

i searched code:

class="lang-ml prettyprint-override">(* delete multiples of p stream *) allow sift p = filter (fun n -> n mod p <> 0) (* sieve of eratosthenes *) allow rec sieve = function | nil -> nil | cons (p, g) -> allow next = sift p (g()) in cons (p, fun () -> sieve next) (* primes *) allow primes = sieve (from 2)

i can understand working. trick?

also how stream of permutation of list?

ocaml

No comments:

Post a Comment