3

In python, with list comprehension, i can pass multiple arguments to a map function's function argument as,

  const = 2 
  def divide(x,y):
    return x/y
  [divide(x, const) for x in [2,4,6,8]]

How can i do the same in haskell using map function?

Something like this,

func x y = x/y

map (func x 2) [2 4 6 8]

I think, it can be done using function currying, but not sure about the correct way?

1 Answer 1

8

using sections

you can use a section like this:

Prelude> let func x y = x / y
Prelude> map (`func` 2) [2,4,6,8]
[1.0,2.0,3.0,4.0]

see when you write a function in backticks you make it into an operator - then you can plug in values to the left or to the right to (for x or y here).

If you wanted to substitute for x then you could have used normal partial application as well:

Prelude> map (func 24) [2,4,6,8]
[12.0,6.0,4.0,3.0]

which is the same as

Prelude> map (24 `func`) [2,4,6,8]
[12.0,6.0,4.0,3.0]

using a lambda

of course if you don't like this at all you can always use lambda's:

Prelude> map (\x -> func x 2) [2,4,6,8]
[1.0,2.0,3.0,4.0]

using list-comprehension

or you can do the same as you did in Python (use a list comprehension):

Prelude> [ func x 2 | x <- [2,4,6,8] ]
[1.0,2.0,3.0,4.0]

ok I think right now I can think of no other (easy) ones ;)

using partial application with flip

flip and partial application (I think a bit less readable - but I find it kind of funny ;):

Prelude> map (flip f 2) [2,4,6,8]
[1.0,2.0,3.0,4.0]

remark / div

as you only dealt with Ints here you probably would want to use div instead of (/):

Prelude> map (`div` 2) [2,4,6,8]
[1,2,3,4]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.