Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble understanding Haskell's type system

I am currently trying to do 20 Intermediate Haskell Exercises. I was able to get done with the 1st 3 exercises (but this is because furry == fmap and Learn You a Haskell has those implementations already). I am currently stuck on the instance that says:

instance Fluffy (EitherLeft t) where                                        
  furry = error "todo"

I am not really understanding what to do. In Learn You Haskell they have a newtype variable called Pair which takes in a tuple. They then can do pattern matching as such:

  fmap f (Pair (x,y)) = Pair (f x, y)

I was thinking maybe you could do something similar in my situation:

  furry f (EitherLeft (Either a b)) = EitherLeft (Either (f a) b)

But, that doesn't work:

Not in scope: data constructor `Either'

I was thinking maybe I would import Data.Either because there might be some import things he has I don't have. But that didn't matter.

I also tried to get just this to work:

  furry f (EitherLeft a b) = error "todo"

But that doesn't work either:

Constructor `EitherLeft' should have 1 argument, but has been given 2

I couldn't get this to work either:

  furry f (Right x) = (Right f x)
  furry f (Left x) = Left x

Which gave the error:

Couldn't match expected type `EitherLeft t a'
            with actual type `Either t0 t1'

I have only been able to get:

  furry f (EitherLeft t) = error "todo"

to work. But I have no idea what to do with t.

I don't necessarily want an answer. I just need a hint as to what to do because I'm reading and I can sort of, understand the examples but I can't really get my head around to coding this stuff right on my own.

Thanks Dan, this is what I came up with for my solution:

instance Fluffy (EitherLeft t) where                     
  furry f (EitherLeft (Left x)) = EitherLeft $ Left  (f x)                   
  furry f (EitherLeft (Right x)) = EitherLeft $ Right x
like image 765
Dair Avatar asked Aug 21 '12 01:08

Dair


Video Answer


1 Answers

The problem you are having is that the Either datatype does not have a data constructor called Either, basically the Either type looks like this

data Either a b = Left a
                | Right b

So a value can have the type Either a b , but there is no value like Either "one" 1 or something like that, but instead Left "one", or Right 1.

So in the case of EitherLeft, similarly its values will look like EitherLeft (Left a) or EitherLeft (Right b), and need to be pattern matched against as such.

like image 75
Dan Feltey Avatar answered Sep 25 '22 21:09

Dan Feltey