Home > Mobile >  Haskell embedded Either
Haskell embedded Either

Time:04-26

I am having trouble understand the answer to this question

Exercise 4.7 Based on our definition of Tuple from the previous exercise, write a function which takes a Tuple and returns either the value (if it’s a one-tuple), a Haskell-pair (i.e., (’a’,5)) if it’s a two-tuple, a Haskell-triple if it’s a three-tuple or a Haskell-quadruple if it’s a four-tuple. You will need to use the Either type to represent this.

fromTuple (One a ) = Left (Left a )
fromTuple (Two a b ) = Left (Right (a,b) )
fromTuple (Three a b c ) = Right (Left (a,b,c) )
fromTuple (Four a b c d) = Right (Right (a,b,c,d))

with the definition of either being

data Either a b = Left a
                  | Right b

I understand the use of the Either type, but cant seem to understand how the embedding works. It seems to me that more than one parameters are being passed into an either.

CodePudding user response:

I guess you are confused by the notation

Right (Left (a,b,c))

Here, the constructor Right is passed a single argument, which is Left (a,b,c).

Similarly, in the same expression, the constructor Left is being passed a single argument, the tuple (a,b,c). Note that this is a single argument, even if it's a tuple.

Finally, note that the result type has the form "either-of-eithers", i.e.

Either (Either _ _) (Either _ _)

where the holes _ must be filled with suitable types (including tuples, in some cases).

  • Related