Component functions in Haskell with arithmetic functions

I am currently learning Haskell and I am trying to play with function composition.

I have written two functions.

let func1 x y = x + y

let func2 t = t*2

However, when I try to compose these two functions, func2 . func1 1 2

I expect to get 6.

Instead, I am getting this error:

   No instance for (Num (a -> b))
      arising from a use of `func1' at <interactive>:1:8-16
    Possible fix: add an instance declaration for (Num (a -> b))
    In the second argument of `(.)', namely `func1 1 2'
    In the expression: func2 . func1 1 2
    In the definition of `it': it = func2 . func1 1 2

      

Can someone explain why this is not working?

+3


source to share


3 answers


A functional app takes precedence over any operators, so your composition is parsed as func2 . (func1 1 2)

. That is, your code tries to compose the number that is the result func1 1 2

as if it were a function. Note that (func2 . func1) 1 2

it doesn't work either, since (.)

it only works with unary functions.



You can use (func2 . func1 1) 2

or use (.)

multiple times in ways that I personally don't like very much to tell the truth. But it's probably best not to use composition at all in this particular case: func2 $ func1 1 2

it does the same thing with less clutter.

+4


source


Due to a lucky bug (distribution right) you can do it with Data.Function.on

import Data.Function

func1 x y = x + y
func2 t = t*2

func3 = func1 `on` func2

-- or just func3 = (+) `on` (2*)

      



In general, you should just use $

for this kind of thing, since this is what you are doing, the application is a function. This is not a real composing job, so you are trying to clamp the square snap into a round hole if using composition.

+3


source


What you are trying to do is not functional composition: you are trying to apply func1 1 2

to func2

what the operator is for $

.

func2 $ func1 1 2

      

+1


source







All Articles