简体   繁体   中英

How do I apply a function to each element of list, when it has two inputs? Haskell

If I have a function with two inputs eg

func x y

how do I apply the function to all elements of a list, with only one input being the elements of a list. so if I have list [1,2,3] and y = 4, how can I use func using each element of the list as x ie

func 1 4
func 2 4
func 3 4

And return the answers in a list.

Prelude functions only.

Use the combination of flip and map function:

map (flip func y) x

Or as @Jubobs points out, you can do this in a more straightforward fashion:

map (\x -> func x y) xs

Explanation: Let's assume your function func has this definition:

func :: Int -> String -> Int
func y z = y

Now, you can flip it's argument using the flip function:

λ> :t (flip func)
(flip func) :: String -> Int -> Int

So, now you can apply the second argument directly to it:

λ> :t (flip func "dummy")
(flip func "dummy") :: Int -> Int

Now, you can use the map function to apply all the elements of the list to this function:

λ> map (flip func "dummy") [1,2,3,4]
[1,2,3,4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM