|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching * Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
rangenim> let r = 1..100 nim> r 1 .. 100 == type HSlice[system.int, system.int] nim> r.a 1 == type int nim> r.b 100 == type int
It doesn't generate a sequence of numbers or iterate by itself — it's just a lightweight object that stores two boundary values (a closed interval). What you do with it depends on the context:
So nim> let r = 1 ..< 5 nim> r 1 .. 4 == type HSlice[system.int, system.int] nim> r.a 1 == type int nim> r.b 4 == type int nim> range to seqimport std/math # sum echo (1..10).sum # ERROR
Solution: make a seq from the range. import std/sequtils # toSeq import std/math # sum echo toSeq(1..10).sum # 55 echo (1..10).toSeq.sum # 55 ; with alternative syntax echo (1..10).toSeq # @[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ExampleLet's see how to pass a range object to a function. func prod*(slice: HSlice[int, int]): int = ## Product of numbers in a slice. runnableExamples: doAssert prod(1..3) == 6 doAssert prod(1..5) == 120 doAssert prod(1..1) == 1 doAssert prod(3..3) == 3 doAssert prod(3..4) == 12 assert 1 <= slice.a and slice.a <= slice.b result = 1 for n in slice: result *= n proc main() = echo prod(1..5) # 120 # ############################################################################ when isMainModule: main() |
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |