`flip` arguments of infix application inline
Asked Answered
T

1

7

Given a function for infix usage:

let f a b = (a+10, b)
f 4 5
=> (14,5)
4 `f` 5
=> (14,5)

The arguments can be flipped by defining a helper function:

let g = flip f
4 `g` 5
=> (15,4)

Is it possible to do this inline?

4 `flip f` 5
=> parse error on input `f'
4 `(flip f)` 5
=>  parse error on input `('

My use case is Control.Arrow.first. Instead of

(+10) `first` (7,8)
(17,8)

I would prefer a forward-application-style solution like

(7,8) `forwardFirst` (+10)

without needing to write

let forwardFirst = flip first
Trappings answered 21/11, 2014 at 9:57 Comment(6)
What's your use case for wanting to do this, given that you have defined g already?Altarpiece
Just added my use case. :)Trappings
This is not a direct answer to your question, but you can write it as (7,8) & _1 %~ (+10) using lens. Of course, you can just use & and write it as (7,8) & first (+10). Is this something similar to what you want?Greenockite
Yes, this looks good, but having Lens as a dependency for something that small seems a bit hard to me.Trappings
Writing a single tiny helper function is definitely better than adding a dependency :)Warden
I agree, but just defining (&) = flip ($) and using it as (7,8) & first (+10) would be better than defining a flipped version of every function.Greenockite
A
1

As detailed in the HaskellWiki article on infix operators,

Note that you can only normally do this with a function that takes two arguments. Actually, for a function taking more than two arguments, you can do it but it's not nearly as nice

The way to do this in your case would be something like this:

let f a b = (a+10, b)
let h a b = (f `flip` a) b
let a = 3
let b = 2
f a b = (13,2)
a `h` b = (12,3)
Altarpiece answered 21/11, 2014 at 10:10 Comment(2)
With g = flip f and h a b = (f 'flip' a) b both functions are the same. Where is the advantage of the more complicated version h?Trappings
Fair point. I'm not really sure if there is a better way to do what you want though.Altarpiece

© 2022 - 2024 — McMap. All rights reserved.