[Haskell-cafe] Are there arithmetic composition of functions?
wren ng thornton
wren at freegeek.org
Tue Mar 20 05:58:58 CET 2012
On 3/19/12 12:57 PM, sdiyazg at sjtu.edu.cn wrote:
> By arithmetic I mean the everyday arithmetic operations used in engineering.
> In signal processing for example, we write a lot of expressions like f(t)=g(t)+h(t)+g'(t) or f(t)=g(t)*h(t).
> I feel it would be very natural to have in haskell something like
You should take a look at Ralf Hinze's _The Lifting Lemma_:
http://www.cs.ox.ac.uk/ralf.hinze/WG2.8/26/slides/ralf.pdf
The fact that you can lift arithmetic to work on functions comes from
the fact that for every type T, the type (T->) is a monad and therefore
is an applicative functor. The output type of the function doesn't
matter, except inasmuch as the arithmetic operations themselves care.
This pattern has been observed repeatedly, even long before Haskell was
around. But one reason it's not too common in production Haskell code is
that it's all too easy to make a mistake when programming (e.g., you
don't mean to be adding functions but you accidentally forget some
argument), and if you're using this trick implicitly by providing a Num
instance, then you can get arcane/unexpected/unhelpful error messages
during type checking.
But then you do get some fun line noise :)
twiceTheSumOf = (+) + (+)
squareTheSumOf = (+) * (+)
cubeTheSumOf = (+) * (+) * (+)
-- N.B., the names only make sense if all arguments
-- are numeric literals. Don't look at the types.
addThreeThings = (+) . (+)
addFourThings = (+) . (+) . (+)
addFiveThings = (+) . (+) . (+) . (+)
--
Live well,
~wren
More information about the Haskell-Cafe
mailing list