F# passing an operator with arguments to a function

后端 未结 3 1143
小蘑菇
小蘑菇 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: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#.

提交回复
热议问题