Why can (++) be used for both adding and adding using a map?

I am currently starting work with Haskell (reading "Learn Yourself Haskell"), and have come across lines similar to the following:

map (++"!") ["a", "b"] -- ["a!", "b!"] map ("!"++) ["a", "b"] -- ["!a", "!b"] 

Why is this possible or how does it work? I cannot do the same with other non-commutative operations such as division:

 map (3/) [1..3] -- [3.0,1.5,1.0] map ((/)3) [1..3] -- [3.0,1.5,1.0] map (3(/)) [1..3] -- error 

It seems to me that something is missing here, but the map implementation does not give me any advice.

+4
source share
3 answers

This code is not valid:

 map (3(/)) [1..3] 

(/) is a prefix function, but you use it as infix. The compiler sees this when trying function 3 (function with no arguments), add (/) as the argument.

/ is a function of infix. So you can do the following:

 map ( / 3) [1..3] -- [0.3333333333333333,0.6666666666666666,1.0] map (3 / ) [1..3] -- [3.0,1.5,1.0] 
+10
source

This is not at all related to the map; maps can just be any function.

To understand the functions you have passed, view this GHCi session:

 Prelude> :t (++"!") (++"!") :: [Char] -> [Char] Prelude> (++"!") "Hello" "Hello!" Prelude> ("!"++) "Hello" "!Hello" Prelude> :t ("!"++) ("!"++) :: [Char] -> [Char] 

Here comes the syntactic idea of ​​the working sections ( Haskell report , section 3.4), which can be read as

 (x •) == (\y. x • y) (• x) == (\y. y • x) 

where can be any operation like ++ , * or even funny self-defined operators, such as ^_^ .

+4
source

If a function is declared in brackets: (++) :: [a] → [a] → [a], it can be used with them without them. If they are used without parentheses, they must be displayed between the arguments: "!" ++ "?" "!" ++ "?" but in parentheses they look like ordinary functions: (++) "!" "?" (++) "!" "?" .

Haskell allows "partial application" of functions, so ("!"++) matches (++) "!" or \x -> (++) "!" x \x -> (++) "!" x , and (++"?") same as \x -> (++) x "?" . (A “partial application” is in quotation marks because functions in Haskell always have only one argument, so the application is no longer “partial”, and in other languages ​​(++) it will be considered as a function of two arguments, therefore, when there is only one argument applied, the function is considered partially applied - in this sense it may be useful to view ("!" ++) as partially applied (++))

The second example is a valid way to use (/), but if you use (/) it is no longer an infix function, so you get an error trying to specify the first argument (/) before the function name: 3(/) . It still works if you remove the brackets: (3 /) matches ((/) 3) or (\x -> (/) 3 x) or (\x -> 3 / x)

0
source

All Articles