Haskell: Using a Map in Functional Composition

I'm relatively new to Haskell, so I apologize if my question sounds stupid. I was trying to understand how function composition works, and I ran into a problem that I was wondering about, someone could help me. I use a map as part of a function in the following two scenarios:

  • map (*2) . filter even [1,2,3,4]
  • map (*2) . zipWith max [1,2] [4,5]

Although the filter and zipWith functions return a list, only the first composition works, and the second composition produces the following error:

"Couldn't match expected type '[Int] -> [Int]' with actual type '[c0]'

Any suggestions are welcome.

+5
source share
5 answers

Recall the type (.).

(.) :: (b -> c) -> (a -> b) -> a -> c

Three arguments are required: two functions and an initial value and returns the result of two functions.

, (.). , :

map (*2) . filter even [1,2,3,4]

:

(.) (map (*2)) (filter even [1,2,3,4])

map (*2) . (b -> c), b c - Num a => [a]. :

Prelude> :t filter even [1,2,3,4]
filter even [1,2,3,4] :: Integral a => [a]

, [a] , (.) .

, :

Couldn't match expected type `a0 -> [b0]' with actual type `[a1]'
In the return type of a call of `filter'
In the second argument of `(.)', namely `filter even [1, 2, 3, 4]'
In the expression: map (* 2) . filter even [1, 2, 3, 4]

... !

$, :

map (*2) . filter even $ [1,2,3,4]

parens,

map (*2) (filter even [1,2,3,4])

:

(map (*2) . filter even) [1,2,3,4]
+16

zipWith max [1,2] [4,5] , . (.) . . ,

map (*2) (zipWith max [1,2] [4,5])

WinHugs (Hugs mode); .

(map (*2) . filter even) [1,2,3,4]

.

+5

:

map (* 2) $ filter even [1, 2, 3, 4]
(map (* 2) . filter even) [1, 2, 3, 4]
map (* 2) $ zipWith max [1, 2] [4, 5]
(\xs -> map (* 2) . zipWith max xs) [1, 2] [4, 5]

:

map (* 2) . filter even [1, 2, 3, 4]
map (* 2) . zipWith max [1, 2] [4, 5]
(map (* 2) . zipWith max) [1, 2] [4, 5]

? , , ,

map (* 2) . zipWith max [1, 2] [4, 5]

,

(map (* 2)) . (((zipWith max) [1, 2]) [4, 5])

(map (* 2)) [Int] -> [Int] (, Int), (((zipWith max) [1, 2]) [4, 5]) [Int] (.) (b -> c) -> (a -> b) -> a -> c ([Int] -> [Int]) -> ([Int] -> [Int]) -> [Int] -> [Int] , . , ($) (a -> b) -> a -> b ([Int] -> [Int]) -> [Int] -> [Int] , :

(map (* 2)) $ (((zipWith max) [1, 2]) [4, 5])

.

+4

- (.), Haskell

map (*2) . filter even [1,2,3,4]

map (*2) . (filter even [1,2,3,4])

. map (*2) () filter even [1,2,3,4] (), .

, @Theodore, ($):

map (*2) . filter even $ [1,2,3,4]
+2

: (a -> b) -> [a] -> [b]

, a b, a b. ?

a b, (*2). , : [Integer] -> [Integer] , .

(.) , . filter even, , : [Integer] -> [Integer], .

Then this composition does not change the final signature of the function if you check the type: map (*2) . filter eventhis[Integer] -> [Integer]

This does not apply map (*2) . zipWith max [1,2] [4,5]because it zipWith maxdoes not have the same signature as expected map (*2).

+2
source

All Articles