[Haskell-beginners] Convert my own types to the Haskell types using typeclass

Bob Ippolito bob at redivi.com
Fri Apr 11 17:05:03 UTC 2014


On Fri, Apr 11, 2014 at 9:50 AM, ke dou <kd6ck at virginia.edu> wrote:

> Hi,
>
> I want to define a typeclass that can convert my own types like MyBool,
> MyInt, MyOption to according Haskell types -- Bool, Int, Maybe.
>
> Currently I can convert the first two types, but for MyOption, I don't how
> to do, since it is a polymophic type.
>
> Here is my toy program:
> --------------------------------------------------------------
> {-# LANGUAGE TypeFamilies #-}
>
> module Coercible where
>
> import qualified Prelude
>
> data MyBool = MyTrue | MyFalse
> data MyInt = Zero | One | Two
> data MyOption a =
>    Some a
>  | None
>
> class Coercible a where
>   type Return a :: *
>   toHaskell :: a -> (Return a)
>
> instance Coercible MyBool where
>   type Return MyBool = Prelude.Bool
>   toHaskell MyTrue = Prelude.True
>   toHaskell MyFalse = Prelude.False
>
> instance Coercible MyInt where
>   type Return MyInt = Prelude.Int
>   toHaskell Zero = 0
>   toHaskell One = 1
>   toHaskell Two = 2
>
> instance Coercible (MyOption a) where
>   type Return (MyOption a) = Prelude.Maybe a
>   toHaskell (Some a) = Prelude.Just a
>   toHaskell None = Prelude.Nothing
> --------------------------------------------------------------------------
> The problem occurs when I am trying to use "toHaskell (Some MyBool)", the
> error message is "Not in scope: data constructor `MyBool'".
> Any hints will be appreciated !!
>

`Some MyBool` isn't valid Haskell. MyBool is the name of a type, there's no
binding or constructor with that name. `toHaskell (Some MyTrue)` evaluates
to `Just MyTrue` as expected.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20140411/b7e1b5bb/attachment.html>


More information about the Beginners mailing list