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
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C#
* D lang.
* Java
* Nim
* Nim2
  + exercises
* XC=BASIC
* old
  ◇C++, ◇Clojure, ◇Scala


[ edit | logout ]
[ sandbox | passwd ]

range

nim> 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

HSlice stands for "heterogeneous slice". It's a simple object with two fields:

  • r.a → the start (1)
  • r.b → the end (100)

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:

  • for i in 1..100 → iterates over the range
  • rand(1..100) → picks a random number in the range
  • array[1..100, int] → defines an array with that index range
  • s[1..3] → slices a string or seq

So 1..100 on its own is just a description of a range — it only does something useful when passed to something that knows how to work with it.

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 seq

import std/math        # sum

echo (1..10).sum       # ERROR

sum() can be applied on a seq, but a range is not a seq.

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]

Example

Let'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()
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 May 03, 20:39