[Haskell-cafe] Function composition questions from a newbie
muad
muad.dib.space at gmail.com
Mon Nov 30 17:31:59 EST 2009
newbie2009 wrote:
>
> I am a newbie. Consider this code:
>
> square x = x * x
> add3 x y z = x + y + z
> add x y = x + y
> composition5 x = (square . add3) x
> composition6 x y = (square . add3) x y
>
> 1) What arguments can i pass to composition5? Please give an example of
> calling it.
> 2) What arguments can i pass to composition6? Please give an example of
> calling it.
> 3) How can I write the function "add" to take any number of arguments? I
> would like to call it either as
> "add 1 2" or "add 1 2 3" etc
>
> Thank you.
>
>
for (1) and (2) you can ask haskell what the types are,
Prelude> :t composition5
composition5 :: (Num (a -> a -> a), Num a) => a -> a -> a -> a
Prelude> :t composition6
composition6 :: (Num (a -> a -> a), Num a) => a -> a -> a -> a
This is a worry, it wants binary operation to be a number but it is not!
There must be an error in the program.
Let us try and fix by changing them to
composition5 x = (square . add x)
composition6 x y = (square . add3 x y) y
now we see:
Prelude> :t composition5
composition5 :: (Num a) => a -> a -> a
Prelude> :t composition6
composition6 :: (Num a) => a -> a -> a
which is reasonable,
Prelude> composition5 1 2
9
Prelude> composition6 3 4
121
As for question 3, one would be better to take a list of numbers and to add
[1,2,3] instead of add 1 2 3. (Something similar to add 1 2 3 is possible in
a couple different way (have a go without using any typeclasses!) but more
advanced than one should like to bother with at this point).
add [] = 0
add (x:xs) = x + add xs
would be fine anyway.
--
View this message in context: http://old.nabble.com/Function-composition-questions-from-a-newbie-tp26570201p26583224.html
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.
More information about the Haskell-Cafe
mailing list