How do I define or write my function in Haskell using a function?

I defined a function in Haskell to be square and then add 1 to all the numbers in the given list. I wanted to write this function with function composition, but unfortunately it doesn't work with dot beetwen functions, but it works when I write my functions with parentheses. I don't understand why it doesn't work with dot, or rather why it doesn't work with function composition?

square :: Int -> Int
square x = x * x

funSqr :: [Int] -> [Int]
funSqr xs = [(square x) | x <- xs]

funAdd1 :: [Int] -> [Int]
funAdd1 xs = [(x + 1) | x <- xs]

funFoldr :: [Int] -> Int 
funFoldr [] = 0
funFoldr (x:xs) = x + (funFoldr xs)

fun :: [Int] -> Int
fun xs = funFoldr(funAdd1(funSqr xs))

      

But

fun :: [Int] -> Int
fun xs = funFoldr.funAdd1.funSqr xs  --Why on earth doesn't it work ?
fun xs = funFoldr.funRek xs        --or rather this way?

      

Can someone light my way?

Thanks a lot Asen

+3


source to share


1 answer


Haskell 101 parsing rules: Function app is more tightly bound than any infix statement. The number of spaces doesn't matter. So

funFoldr.funAdd1.funSqr xsfunFoldr . funAdd1 . funSqr xsfunFoldr . funAdd1 . (funSqr xs)

      

Now is funSqr xs

no longer a function (just the result of applying a function to xs

). You cannot create things that are not functions.

What you wanted to try is this, and it actually works:

(funFoldr.funAdd1.funSqr) xs

      

Most often it is written



funFoldr . funAdd1 . funSqr $ xs

      

or

funFoldr . funAdd1 $ funSqr xs

      

Alternatively, you can avoid grouping by funSqr xs

simply not mentioning xs

:

fun :: [Int] -> Int
fun = funFoldr . funAdd1 . funSqr

      

This is called mindless style.

+6


source







All Articles