[Haskell-beginners] Re: Real world example of Typeclasses >
Interfaces
Ertugrul Soeylemez
es at ertes.de
Mon Sep 6 10:47:21 EDT 2010
Alec Benzer <alecbenzer at gmail.com> wrote:
> I was speaking more generally, not specifically about the Haskell
> typeclasses Num and Enum (although actually irrational numbers aren't
> enumerable now that I think of it, but I also guess that's a
> relatively moot point since you can't really represent irrational
> numbers in a programming language)
There is a Num instance, which doesn't make sense to be an Enum
instance:
instance Num a => Num (a -> a) where
f + g = \x -> f x + g x
-- ...
This makes some formulas look much nicer and more convenient to write:
constOne :: Floating a => a -> a
constOne = sin^2 + cos^2
Unfortunately Eq and Show are superclasses of Num, so you need a few
bogus instances:
instance Eq (a -> a) where
(==) = undefined
instance Show (a -> a) where
show = const "<function>"
As an alternative you can do this with the reader functor, too, although
it doesn't look nearly as nice for the above formula:
constOne :: Floating a => a -> a
constOne = (+) <$> (^2) . sin <*> (^2) . cos
It looks great for other formulas, though, and is more general:
splits :: [a] -> [([a], [a])]
splits = zip <$> inits <*> tails
Greets,
Ertugrul
--
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/
More information about the Beginners
mailing list