Reputation:
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?
Upvotes: 3
Views: 2515
Reputation: 52280
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]
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]
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 ;)
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]
div
as you only dealt with Int
s here you probably would want to use div
instead of (/)
:
Prelude> map (`div` 2) [2,4,6,8]
[1,2,3,4]
Upvotes: 8