Cyclical Type Synonyms

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Cyclical Type Synonyms

Tom Hawkins-2
I want to define a type for a function that returns its own type...

type F a = a -> (F a,a)

But the compiler gives me an error: "Cycle in type synonym declaration: ...".

Why is this a restriction?

Of course I can create a user defined type, but then I need an extra
mechanism to call the embedded function:

data F a = F (a -> (F a ,a))

call :: F a -> a -> (F a, a)
call (F f) a = f a

-Tom
_______________________________________________
Haskell-Cafe mailing list
[hidden email]
http://www.haskell.org/mailman/listinfo/haskell-cafe
Reply | Threaded
Open this post in threaded view
|

Re: Cyclical Type Synonyms

Cale Gibbard
This is because 'type' only allows you to define synonyms for existing
types, not create new types altogether (for that, use newtype). The
synonyms are expanded to their definitions early on in compilation. In
this case, that expansion process would not terminate (but the
compiler is clever enough to realise that).

While you can't have the type synonym you wanted, you can construct a
type which should have no extra runtime baggage by using newtype, and
use record syntax to define call automatically.

newtype F a = F { call :: a -> (F a, a) }

As far as I know, all types in Haskell can be written as a finite tree
of type constructors. There are some tricks one can play with
typeclasses though. See Text.Printf in the Hierarchical libraries for
a good example of that.

 - Cale

On 16/02/06, Tom Hawkins <[hidden email]> wrote:

> I want to define a type for a function that returns its own type...
>
> type F a = a -> (F a,a)
>
> But the compiler gives me an error: "Cycle in type synonym declaration: ...".
>
> Why is this a restriction?
>
> Of course I can create a user defined type, but then I need an extra
> mechanism to call the embedded function:
>
> data F a = F (a -> (F a ,a))
>
> call :: F a -> a -> (F a, a)
> call (F f) a = f a
>
> -Tom
> _______________________________________________
> Haskell-Cafe mailing list
> [hidden email]
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
_______________________________________________
Haskell-Cafe mailing list
[hidden email]
http://www.haskell.org/mailman/listinfo/haskell-cafe