F# passing an operator with arguments to a function

后端 未结 3 1120
小蘑菇
小蘑菇 2021-01-04 11:02

Can you pass in an operation like \"divide by 2\" or \"subtract 1\" using just a partially applied operator, where \"add 1\" looks like this:

List.map ((+) 1         


        
相关标签:
3条回答
  • 2021-01-04 11:25

    There are no 'operation sections' in F#, a la Haskell, nor placeholder arguments (apparently a la Arc). You can use a 'flip' combinator as suggested in another answer to reverse the order of arguments and then partially apply the first (now second) argument.

    But I would just use

    fun x -> x / 2
    

    Unless you're playing code-golf, I don't think trying to shave another few characters off here buys you anything.

    0 讨论(0)
  • 2021-01-04 11:28

    You could write a flip function, something like:

    let flip f x y = f y x
    
    List.map (flip (-) 1) [2;4;6]
    

    I may have the syntax wrong, I'm not terribly fluent in F#.

    0 讨论(0)
  • 2021-01-04 11:31

    The flip-solution suggested by Logan Capaldo can also be written using a operator (here >.):

    let (>.) x f = (fun y -> f y x)
    List.map (1 >. (-)) [2;4;6]
    

    Or if you prefer the operands the other way around:

    let (>.) f x = (fun y -> f y x)
    List.map ((-) >. 1) [2;4;6]
    

    Edit: Using an operator that "looks more like a placeholder" (here >-<) gets you very close to your suggested syntax:

    List.map ((-) >-< 1) [2;4;6]
    

    '_' is unfortunatly(?) not a valid operator symbol in F#.

    0 讨论(0)
提交回复
热议问题