'Haskell embedded Either
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.
Solution 1:[1]
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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chi |
