0

I have this assignment where I am unsure where to start. So one of the things is to do a maybe to either conversion with this signature:

maybeEither:: Maybe a -> Either () a

and the other is of course the opposite

eitherMaybe:: Either () a -> Maybe a

so when you call one of the other they will cancel eachother out. Now I don't really know where to begin here... Can someone help?

Extra question: How would I convert a function for example (Int->a) -> a and a -> (Int->a) Like since in the second example you really can't give the function as a parameter to the function that converts, Im not sure how that would go.

Sibi
  • 47,472
  • 16
  • 95
  • 163
Fatalgoddess
  • 119
  • 1
  • 8

2 Answers2

8

First of all, these are not typeclasses, they're data types. If you're unfamiliar with the difference, I would recommend reading the relevant chapters in Learn You a Haskell.


To solve this particular problem, you just need to pattern match on the different constructors:

maybeEither :: Maybe a -> Either () a
maybeEither Nothing = ???
maybeEither (Just a) = ???

And

eitherMaybe :: Either () a -> Maybe a
eitherMaybe (Left x) = ???
eitherMaybe (Right y) = ???

You just need to fill in the the ???s and you're done.


For your extra question, remember that the signature a -> (Int -> a) is the same as a -> Int -> a, since -> is right associative.

bheklilr
  • 53,530
  • 6
  • 107
  • 163
1

Actually it's very simple, just follow the types to see what you get. The type signature of maybeEither suggests that it takes Maybe a as input.

Maybe is defined like this:

data Maybe a = Just a | Nothing

Also, from the type sigature, you can get that maybeEither gives Either () a as the output for the function.

Either type constructor is defined like this:

data Either a b = Left a | Right b

Now, replace a with () and you will get:

Either () b = Left () | Right b

Or you can replace your type variables to make it clear,

Either () a = Left () | Right a

Now, the implementation of the function is pretty straightforward.

maybeEither :: Maybe a -> Either () a
maybeEither (Just x) = ??? -- fill these
maybeEither Nothing = ???

You can follow the same approach for your other function.

Sibi
  • 47,472
  • 16
  • 95
  • 163
  • 2
    May I suggest you remove the `data` keyword from versions where you substitute in for the type variable? – dfeuer Jun 26 '14 at 23:40
  • @dfeuer Thanks, but can I know why ? `()` is just another type having `()` as a value. – Sibi Jun 27 '14 at 00:56
  • 1
    I don't think it's valid Haskell! A `data` declaration has one type constructor and perhaps several type variables. `()` is a type constructor, not a type variable. You can write the equation `Either () a = Left () | Right a`, but I don't think there's any way to express that *directly* in Haskell, so it's best not to pretend you are. – dfeuer Jun 27 '14 at 15:53