3

Let's define an arbitrary function

someFunc a b = ...

if I ever need it, I know I can do something like

map (someFunc a) [b0, b1, b2, ..., bn]

and I'll get as result

[(someFunc a b0), (someFunc a b1), ..., (someFunc a bn)]

There is nothing new here. But what if instead of using the map's 2nd argument to vary b, I wanted to vary a (a "inner" argument)?

map (someFunc ? b) [?0, ?1, ?2, ..., ?n]

Is there any way to accomplish this in Haskell? If not, what would be the work around for this?

I know I probably wasn't very clear about what I'm posting about. If needed, I can try to reformulate my question :(

1
  • Trust me (or anyone who did a bit of Haskell) - you'll need implicit currying. Propably because it becomes second nature, but at the very least so you can read the code point-free fanatics sometimes produce. Commented Dec 1, 2010 at 22:36

2 Answers 2

11

You can either use a lambda

map (\a -> someFunc a b) ...

or the higher order functionflip, which returns the given function with its arguments flipped around:

map (flip someFunc b) ...
Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget (ab)using backticks and infix sections, e.g. (`someFunc` b). Usually not recommended, but can be acceptable for two-argument functions and/or functions intended to be used infix, like on.
4

You could use

flip :: (a -> b -> c) -> b -> a -> c

So you would say

map (flip someFunc b) [a1...]

For more complicated cases with more arguments you would have to use a lambda. In theory you can always do it with the right combination of flips and arguments, but the lambda version will probably be more readable.

1 Comment

You could also use lots and lots of flips: \x -> f x a1 a2 a3 a4 a5, for instance, is equivalent to flip (flip (flip (flip (flip f a1) a2) a3) a4) a5 (code obtained via the pointfree program). But, uh, don't do this :-)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.