-

   rss_rss_hh_new

 - e-mail

 

 -

 LiveInternet.ru:
: 17.03.2011
:
:
: 51

:


[ ] Nim

, 19 2017 . 13:10 +
  Nim

! , generic converter Nim ( )

Nim? Nim ( C, C++, Objective C JS) , ( ): , , . , GitHub.
Nim (, , ).

, , int, int:

proc plusOne(arg: int): int = 
  return arg + 1
echo plusOne(5)  #  6

, ( 1 arg int )

Nim , ( , ).

1


, len ( __len__ Python):

proc tryLen[T](something: T) = 
  when compiles(something.len):  # something.len   ,  len(something)
    echo something.len
  else:
    echo "      `len`"

#    ,      `len` (     )
type MyObject = object
#   
let myObj = MyObject()
tryLen([1, 2, 3])  #  3
tryLen("Hello world!")  #  12
tryLen(myObj)  #  "      `len`"

, , :

tryLen, something T (T , T abcd, ).
when compiles ( if, , when ). len , .
MyObject, tryLen [1, 2, 3], Hello world!, .

2


( , - ).
, MyObject ( 1):

type MyObject = object
let myObj = MyObject()

#     ,        return
#     -  
converter toInt(b: MyObject): int = 1
#     (       )
echo myObj.toInt + 1  #  2
#      :
echo myObj + 1  #   2,   toInt   myObj   1

( ), .


, , . Nim Python ( bool)

converter toBool[T](arg: T): bool = 
  #        len
  when compiles(arg.len):
    arg.len > 0
  #          T
  # T(0)   ,    
  #     (.   0   )
  elif compiles(arg + T(0)):
    arg > 0


if [1, 2, 3]:  #  
  echo "True!"
if @[1, 2, 3]:  #  
  echo "True too!"
if "":  #  
  echo "No :("
if 5:  # Integer
  echo "Nice number!"
if 0.0001:  # Float
  echo "Floats are nice too!"

! , - .



Nim, .
Original source: habrahabr.ru (comments, light).

https://habrahabr.ru/post/333702/

:  

: [1] []
 

:
: 

: ( )

:

  URL