Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Nim2
* Scala


[ edit | logout ]
[ sandbox | passwd ]

Uniform Function Call Syntax (UFCS)

Nim supports the so-called Uniform Function Call Syntax (UFCS). It's an awesome thing, though not many languages support it (D, for instance, knows it).

Let's see this example:

func is_even(n: int): bool =
  n mod 2 == 0

echo is_even(4)  # true
echo is_even(9)  # false

With UFCS, you can move the first argument to the left side and call the function as if it were a method:

echo 4.is_even()  # true; the compiler will call is_even(4)

It works :) Although Nim is not really an object-oriented language, thanks to UFCS you can use a syntax that is common in OO languages: obj.method() . In C#, if you want something similar, you need to write an extension method. Here, you get it for free.

What if you have multiple arguments?

func add(a, b: int): int = a + b

echo add(3, 5)  # 8

echo 3.add(5)  # 8; converted to add(3, 5)

The value before the dot is passed as the first argument.


This is not UFCS, but closely related IMO, so I put it here:

If a function has no argument, the parentheses can be omitted:

echo 4.is_even  # true

I prefer adding the parentheses, that syntax makes it clear that we call a function. However, if you want, you can drop the parentheses.

Furthermore, if a function has just one argument, then you can also omit the parentheses. These two are equivalent:

discard is_even(4)

discard is_even 4

I don't recommend using it, but it's also possible. Here I had to add discard to avoid a compiler error (since we do nothing with the returned value).

Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 April 04, 13:54