[Haskell-cafe] Re: snd and tuples of various sizes...
Max Vasin
max.vasin at gmail.com
Fri Feb 2 08:49:06 EST 2007
>>>>> "Mattias" == Mattias Bengtsson <moonlite at dtek.chalmers.se> writes:
Mattias> On Thu, 2007-02-01 at 21:01 -1000, Tim Newsham wrote:
>> instance Second [a] a where snd [] = error "don't got none" snd
>> (x:y:xs) = y
Mattias> Would'nt that instance mean this: snd [] produces error
Mattias> snd [x] gives []
No. It is non-exhaustive pattern. In fact this is needed:
> instance Second [a] a where
> snd (_:y:_) = y
> snd _ = error "don't got none"
Mattias> I'd implement it something like this (if this works?):
Mattias> instance Second [a] (Maybe a) where snd [] = Nothing snd
Mattias> [x] = Nothing snd (x:y:xs) = Just y
Well, we also can define:
> class SafeSecond a b | a -> b where
> ssnd :: (Monad m) => a -> m b
> instance SafeSecond [a] a where
> ssnd (_:y:_) = return y
> ssnd _ = fail "don't got none"
> main = do
> print $ (ssnd [1, 2, 3] :: Maybe Int)
> print $ (ssnd [1] :: Maybe Int)
--
WBR,
Max Vasin.
More information about the Haskell-Cafe
mailing list