Answer the question
In order to leave comments, you need to log in
How does composition work in Haskell?
Please explain how this function works:
import Data.Char
digitSum :: Int -> Int
digitSum = sum.map digitToInt.show
how is it that the show function converts a number into a string and at the same time returns it not to the digitToInt function, but to the map function and is itself given as the first argument to map.
Logically, show should pass to digitToInt based on (.) :: (b -> c) -> (a -> b) -> a -> c, but the pass is somehow intercepted by the digitToInt
map :: Char -> Int
rather, you can do it like this digitSum = sum.(map digitToInt).show , but I don’t understand why this happens.
Answer the question
In order to leave comments, you need to log in
1) y = show x
where x is a number. The result y is a string
2) z = map digitToInt y
digitToInt maps all characters (digits of the original number x to numbers). The result z is a list of numbers.
Those. x = 125, y = "125" or ['1', '2', '5'], z = [1, 2, 5]
3) sum z calculates the sum of the list, in our case the sum of the digits of the original multi-digit number.
The answer to the last question is this. The function has the highest priority (10), so map "pulls" the digitToInt argument. The composition OPERATOR has priority, like, 9. Therefore, the last example is equivalent to the original one and the parentheses are not required. True, it is advised to put spaces around the dot (composition operator) for clarity.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question