Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when trying to use function composition in Haskell

I have just began recently to learn Haskell, more specifically on the topics of function composition, partial functions, maps, filters and sectioning. On one of the exercises am asked to modify the twoFilters function by using function composition.

I have read a few wikis on . but am having quite a hard time getting it to work correctly. As i understand it, it works by performing the functions b . a on alphabetical order and returning the result. In other words x = foo a and then foo b of x. However after applying several "variations/possibilities" with the bellow two filters functions i cant get it to compile due to errors.

greaterThanOne :: Int -> Bool
greaterThanOne = (>1)

lessThanTen :: Int -> Bool
lessThanTen = (<10)

twoFilters :: [Int] -> [Int]
twoFilters xs= filter lessThanTen (filter greaterThanOne xs)

These two being the unsuccessful attempts I had most confidence on;

twoFilters xs = filter (lessThanTen . greaterThanOne xs)

twoFilters xs = filter (lessThanTen xs . greaterThanOne xs)

Where on the reasoning am I going wrong?

like image 540
Carlos Avatar asked Dec 17 '22 17:12

Carlos


1 Answers

The attempts you were confident about are a simple failure in your logic: the dot operator works like this:

(f.g)(x) = f(g(x))

So, trying to compute an example of 5 gives:

lessThanThen(greaterThanOne(5)) = lessThanTen(True) -- that can't be right, can it???

What you want is a lambda and &&:

filter (\x-> (lessThanThen x) && greaterThanOne(x))

Alternatively, you can use two filters:

filter lessThanTen . filter greaterThanOne $

like image 85
user268396 Avatar answered Feb 09 '23 03:02

user268396