Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an infix function

Tags:

f#

Is there a way to write an infix function not using symbols? Something like this:

let mod x y = x % y
x mod y

Maybe a keyword before "mod" or something.

like image 445
Iter Avatar asked May 14 '13 16:05

Iter


People also ask

How do you define an infix function?

What are infix functions? In R, most of the functions are “prefix” - meaning that the function name comes before the arguments, which are put between parentheses : fun(a,b) . With infix functions, the name comes between the arguments a fun b . In fact, you use this type on a daily basis with : , + , and so on.

How do you define an infix function in Haskell?

There's no way to define a function with an alphanumeric name as infix. Haskell's syntax rules only allow for functions with symbolic names or function names surrounded with backticks to be used infix - there's no way to change that.

What is the use of infix function in Kotlin?

Kotlin allows some functions to be called without using the period and brackets. These are called infix methods, and their use can result in code that looks much more like a natural language.


1 Answers

The existing answer is correct - you cannot define an infix function in F# (just a custom infix operator). Aside from the trick with pipe operators, you can also use extension members:

// Define an extension member 'modulo' that 
// can be called on any Int32 value
type System.Int32 with
  member x.modulo n = x % n

// To use it, you can write something like this:
10 .modulo 3

Note that the space before . is needed, because otherwise the compiler tries to interpret 10.m as a numeric literal (like 10.0f).

I find this a bit more elegant than using pipeline trick, because F# supports both functional style and object-oriented style and extension methods are - in some sense - close equivalent to implicit operators from functional style. The pipeline trick looks like a slight misuse of the operators (and it may look confusing at first - perhaps more confusing than a method invocation).

That said, I have seen people using other operators instead of pipeline - perhaps the most interesting version is this one (which also uses the fact that you can omit spaces around operators):

// Define custom operators to make the syntax prettier
let (</) a b = a |> b
let (/>) a b = a <| b    
let modulo a b = a % b 

// Then you can turn any function into infix using:
10 </modulo/> 3

But even this is not really an established idiom in the F# world, so I would probably still prefer extension members.

like image 120
Tomas Petricek Avatar answered Oct 06 '22 23:10

Tomas Petricek