[Haskell-cafe] showing a user defined type

michael rice nowgate at yahoo.com
Tue May 19 19:25:57 EDT 2009

Hi Ryan,

I'm afraid you've lost me. Maybe if you showed how this would be used in ML I would get the picture.


--- On Tue, 5/19/09, Ryan Ingram <ryani.spam at gmail.com> wrote:

From: Ryan Ingram <ryani.spam at gmail.com>
Subject: Re: [Haskell-cafe] showing a user defined type
To: "michael rice" <nowgate at yahoo.com>
Cc: "Brandon S. Allbery KF8NH" <allbery at ece.cmu.edu>, haskell-cafe at haskell.org
Date: Tuesday, May 19, 2009, 2:40 PM

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 #   (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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090519/8415da8e/attachment.html

More information about the Haskell-Cafe mailing list