[Haskell-beginners] Help in pattern matching
Magnus Therning
magnus at therning.org
Mon Mar 8 07:06:48 EST 2010
On Mon, Mar 8, 2010 at 11:28, Stephen Tetley <stephen.tetley at gmail.com> wrote:
> Hi Magnus
>
> That's not quite equivalent to Joe Fox's original code, although it is
> an improvement as test in the original won't type check:
>
> original...
>
> test (DataConst1 x y) = x -- returns Int
> test (DataConst2 x y) = x -- returns Int
> test (DataConst3 x y) = y -- returns String
> test (DataConst4 x y) = y -- returns Int
>
>
> This one does type check...
>
> test2 :: TestData -> Either Int String
> test2 (DataConst1 x y) = Left x
> test2 (DataConst2 x y) = Left x
> test2 (DataConst3 x y) = Right y
> test2 (DataConst4 x y) = Left y
I don't see where it's different from my code (i.e. modulo the
ordering of 'Either ...').
Now I may be missing something, but defining a conversion function and
running smallcheck (or I guess quickcheck) shows that
'prop_test2EqTestM' holds (I took the liberty of swapping the Either
around compared to your 'test2' above):
data TestData = DataConst1 Int String
| DataConst2 Int Int
| DataConst3 String String
| DataConst4 String Int
test2 (DataConst1 x _) = Right x
test2 (DataConst2 x _) = Right x
test2 (DataConst3 _ y) = Left y
test2 (DataConst4 _ y) = Right y
type TestDataM = (Either String Int, Either String Int)
testM :: TestDataM -> Either String Int
testM (x@(Right _), _) = x
testM (Left _, y) = y
conv2Tuple :: TestDataM -> TestData
conv2Tuple (Right x, Left y) = (DataConst1 x y)
conv2Tuple (Right x, Right y) = (DataConst2 x y)
conv2Tuple (Left x, Left y) = (DataConst3 x y)
conv2Tuple (Left x, Right y) = (DataConst4 x y)
prop_test2EqTestM tdm = let
td = conv2Tuple tdm
in
test2 td == testM tdm
What am I missing?
/M
--
Magnus Therning (OpenPGP: 0xAB4DFBA4)
magnus@therning.org Jabber: magnus@therning.org
http://therning.org/magnus identi.ca|twitter: magthe
More information about the Beginners
mailing list