|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching * Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
named tuple with custom typePreviously, we saw this example: func getMovieInfo(): (string, int, float) = return ("Total Recall", 1990, 7.5) let (title, year, score) = getMovieInfo() # !!! on the left side, use parentheses !!! echo title # Total Recall echo year # 1990 echo score # 7.5 Let's put a type on the tuple: type Movie = tuple[title: string, year: int, score: float] func getMovieInfo(): Movie = return (title: "Total Recall", year: 1990, score: 7.5) # return ("Total Recall", 1990, 7.5) # it would also work let m = getMovieInfo() echo m.title # Total Recall echo m.year # 1990 echo m.score # 7.5 You can also use the following syntax. It's equivalent to the previous: type Movie = tuple title: string year: int score: float However, we might ask ourself: why do we use a tuple here? Why don't we use a normal object? Same thing with a "class" and objecttype Movie = object title: string year: int score: float func getMovieInfo(): Movie = return Movie(title: "Total Recall", year: 1990, score: 7.5) let m = getMovieInfo() echo m.title # Total Recall echo m.year # 1990 echo m.score # 7.5 The main difference is in the construction of the tuple/object: # tuple: return ("Total Recall", 1990, 7.5) # or: return (title: "Total Recall", year: 1990, score: 7.5) # object: return Movie(title: "Total Recall", year: 1990, score: 7.5) Unfortunately, Nim does not support positional object construction by default. You must use the named field syntax. Let's add a constructor procedureWhat if we don't want to indicate the field names every time when we create a Movie object? Well, there is an idiomatic Nim pattern for object construction — defining a Here it is: type Movie = object title: string year: int score: float # new thing: proc newMovie(title: string, year: int, score: float): Movie = return Movie(title: title, year: year, score: score) func getMovieInfo(): Movie = #return Movie(title: "Total Recall", year: 1990, score: 7.5) return newMovie("Total Recall", 1990, 7.5) let m = getMovieInfo() echo m.title # Total Recall echo m.year # 1990 echo m.score # 7.5 Now, the object creation is very similar to the tuple creation: # tuple: return ("Total Recall", 1990, 7.5) # object: return newMovie("Total Recall", 1990, 7.5) I have the impression that in most cases, using an object is cleaner and more extensible. However, tuples still have their place when you need destructuring.
|
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |