f# - How to write an infix function -
is there way write infix function not using symbols? this:
let mod x y = x % y x mod y
maybe keyword before "mod" or something.
the existing answer correct - cannot define infix function in f# (just custom infix operator). aside trick pipe operators, can use extension members:
// define extension member 'modulo' // can called on int32 value type system.int32 member x.modulo n = x % n // use it, can write this: 10 .modulo 3
note space before .
needed, because otherwise compiler tries interpret 10.m
numeric literal (like 10.0f
).
i find bit more elegant using pipeline trick, because f# supports both functional style , object-oriented style , extension methods - in sense - close equivalent implicit operators functional style. pipeline trick looks slight misuse of operators (and may confusing @ first - perhaps more confusing method invocation).
that said, have seen people using other operators instead of pipeline - perhaps interesting version 1 (which uses fact can omit spaces around operators):
// define custom operators make syntax prettier let (</) b = |> b let (/>) b = <| b let modulo b = % b // can turn function infix using: 10 </modulo/> 3
but not established idiom in f# world, still prefer extension members.
Comments
Post a Comment