|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching • Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
anonymous tuplesIn Python, a tuple is immutable. In Nim, it depends on how you decared it: with import typetraits # echo n.type.name var t = ("Banana", 2, 'c') echo t # ("Banana", 2, 'c') echo t.type.name # (string, int, char) <-- this is its type echo t[0] # Banana #echo t[^1] # Error: it won't return the last element :( t[0] = "Kiwi" echo t # ("Kiwi", 2, 'c') # echo t.len # Error: len doesn't work with tuples :( echo tupleLen(typeof(t)) # 3; number of elements Receiving a tuple in a functionWhen we pass a tuple to a function, how to receive it? proc show_last_column(t: tuple[a: string, b: string, c: string, d: int]) = echo t.d let tup = ("001", "Albany", "NY", 162692) show_last_column(tup) Or, alternatively: proc show_last_column(t: (string, string, string, int)) = echo t[3] let tup = ("001", "Albany", "NY", 162692) show_last_column(tup) Return multiple values from a functionLike in Python: func getMovieInfo(): (string, int, float) = return ("Total Recall", 1990, 7.5) let t = getMovieInfo() echo t # ("Total Recall", 1990, 7.5) echo t[1] # 1990 let (title, year, score) = getMovieInfo() # !!! on the left side, use parentheses !!! echo title # Total Recall echo year # 1990 echo score # 7.5 GotchaNim has a surprising behaviour that can be strange after Python: var a, b = 3 #[ it's short for: var a = 3 var b = 3 ]# echo a, " ", b # 3 3 var x, y = f() #[ short for: var x = f() var y = f() That is: f() is called twice! ]# let title, year, score = getMovieInfo() #[ short for: let title = getMovieInfo() let year = getMovieInfo() let score = getMovieInfo() Ooops! This is not what we wanted. ]# If you want to do value unpacking from a tuple, don't forget the parentheses around the variables: let (title, year, score) = getMovieInfo() # !!! on the left side, use parentheses !!! Iterate over the values in a tupleThe let t = (1, "hello", 3.14) for value in t.fields: echo value Output: 1 hello 3.14 Anonymous tuples are comparablelet ta = (2, 8) tb = (2, 8) tc = (3, 12) echo ta == tb # true echo ta == tc # false |
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |