[Haskell-cafe] showing a user defined type

Ryan Ingram ryani.spam at gmail.com
Tue May 19 14:40:55 EDT 2009


On Tue, May 19, 2009 at 7:07 AM, michael rice <nowgate at yahoo.com> wrote:
> A little further along in "The Little MLer" the ints function is replaced by
> other functions like primes and fibs, which also return Links:
>
> fun primes(n)
>   = if is_prime(n+1)
>  then Link(n+1,primes)
>  else primes(n+1)
>
> fun fibs(n)(m)
>   = Link(n+m,fibs(m))
>
> which are passed to chain_item:
>
> fun chain_item(n,Link(i,f))
>   = if eq_int(n,1)
>   then i
>   else chain_item(n-1,f(i))
>
> which can be called to request the nth (12th) prime number beginning at 1.
>
> - chain_item(12,primes(1));
> GC #0.0.0.1.3.61:   (1 ms)
> val it = 37 : int
> -
>
> So I guess the answer to your question about whether the function is ever
> called with a different value may be, yes.

Actually, it's not calling it with another value; notice that
chain_item calls f(i), with i coming directly from the chain.
Consider this alternate definition:
(I'm not sure the syntax is exactly right, but you get the idea)

datatype chain =
  Link of (int * ( unit -> chain ))

fun intsFrom(n) = fun unit => (n, intsFrom (n+1))
fun ints(n) = intsFrom n ()

Now you *can't* call the function embedded in the link with another value.

fun chain_item(n,Link(i,f))
  = if eq_int(n,1)
  then i
  else chain_item(n-1,f unit)

And this type for "chain" is almost the same as [Int] in Haskell, due
to laziness.

  -- ryan


More information about the Haskell-Cafe mailing list