Num instance for functions

From HaskellWiki
Revision as of 01:24, 28 December 2014 by Blackout (talk | contribs) (Refurbish very patchy article to contain the essentials)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

It is possible to write a Num instance for functions in Haskell:

instance Num b => Num (a -> b) where
      negate      = fmap negate
      (+)         = liftA2 (+)
      (*)         = liftA2 (*)
      fromInteger = pure . fromInteger
      abs         = fmap abs
      signum      = fmap signum

This allows writing expressions of the form

> (sin^2 + cos^2) 123.4
1.0

where functions can be added like Numbers, leaving their arguments open for later.

The usefulness of this instance is debatable, and it is not currently part of the language report or defined in any popular library.

See also