Arthur
Arthur

Reputation: 347

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 e.g

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 i.e

func 1 4
func 2 4
func 3 4

And return the answers in a list.

Prelude functions only.

Upvotes: 2

Views: 257

Answers (1)

Sibi
Sibi

Reputation: 48644

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]

Upvotes: 6

Related Questions