V: Infix function Support

Created on 13 Jul 2019  ·  5Comments  ·  Source: vlang/v

V is a very young language, that's why it could maybe support recent concepts like the infix functions.

What?

Basically, an infix function is :

  • a function on an object
  • contains only one parameter
  • is called like an operator
    (instead of user.can_register(16), it can be called by user can_register 16)

Why?

It increases readability.
Also, some operators like in could be infix functions instead of operators (so anyone could create "operators" like not_in or anything else).

How?

The idea is well described here: https://kotlinlang.org/docs/reference/functions.html#infix-notation

In V, a classic method could be described as :

struct User {
    age int 
} 

fn (u User) can_register(age_min int) bool {
    return u.age > age_min 
} 

user := User{age: 10} 
ok := user.can_register(16) // ==> "false"  

An infix function could be simply declared the same way, but adding the keyword infix, like this :

struct User {
    age int 
} 

infix fn (u User) can_register(age_min int) bool {
    return u.age > age_min 
} 

user := User{age: 10} 
ok := user can_register 16 // ==> "false"  
Combination with lambda

The infix functions can be combined with lambda (see #1066)

Example :

ints := [1, 2, 3]
doubled_ints := ints.map(fn (x int) {
  return x * 2
})

//could be replaced by 

doubled_ints := ints map { i ->
   return i * 2
}
Feature Request

Most helpful comment

Personally I love the idea, but I don't know that it coincides with v's philosophy of "one way to do things"

All 5 comments

Personally I love the idea, but I don't know that it coincides with v's philosophy of "one way to do things"

Lets just have “one way to do things", no more “infix” please. :)

user can_register 16

I think you need a better example, that looks like infix abuse to me.

The map example would be:

doubled_ints := ints map fn(i){
   return i * 2
}

I'm not sure that infix is the right feature here, because it doesn't work for more than one argument:
ints.reduce(1, fn (acc, e) acc *= e)

Thanks, but this complicates the language and adds another way of declaring/calling methods. This goes against the philosophy of V.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

elimisteve picture elimisteve  ·  3Comments

medvednikov picture medvednikov  ·  3Comments

jtkirkpatrick picture jtkirkpatrick  ·  3Comments

penguindark picture penguindark  ·  3Comments

arg2das picture arg2das  ·  3Comments