rohaldb
rohaldb

Reputation: 588

Changing parameter order of the function given to map

Say for example we had a function

divide :: Float -> Float -> Float
divide x y = x / y

And a list let list = [1,2,3]

I know i can apply the divide function to the list like so: map (divide 3) temp

But what if I wanted to swap the order of the parameters passed to the divide method, so that each element of the list is divided by 3, rather than 3 being divided by the element.

Something like the following map (divide temp) 3.

Additionally, what if divide had 3 parameters and each element of the list needed to be the middle parameter. How would one do this?

Upvotes: 1

Views: 199

Answers (2)

tauli
tauli

Reputation: 1420

You can either use divide as an infix-operator by enclosing it in backtics like this

map (`divide` 3) temp

or, if you run into a more complicated case in the future, write a lambda (anonymous function)

map (\x -> divide x 3) temp

You may also want to take a look at this more detailed explanation https://wiki.haskell.org/Anonymous_function

Upvotes: 2

Carcigenicate
Carcigenicate

Reputation: 45806

Just make the function parameter an explicit lambda instead of a partially applied function:

map (\n -> divide n 3) temp

Upvotes: 1

Related Questions