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 ]

Check if a text is ASCII only

We have a text and we want to test if it consists of ASCII characters only.

import std/sequtils    # all
import std/unicode     # Rune


func isAscii(c: char): bool =
  ord(c) < 128

func isAscii(r: Rune): bool =
  ord(r) < 128

func isAscii(s: string): bool =
  s.all(isAscii)


let
  s1 = "hello world 2026"
  s2 = "László"
  c1 = 'a'
  c2 = "é".runeAt(0)
  c3 = "a".runeAt(0)

echo s1.isAscii   # true
echo s2.isAscii   # false
echo c1.isAscii   # true
echo c2.isAscii   # false
echo c3.isAscii   # true

You can also join the first two functions:

func isAscii(c: char | Rune): bool =
  ord(c) < 128

func isAscii(s: string): bool =
  s.all(isAscii)

Now the first function is a generic function. Actually, it's just syntactic sugar for the longer form:

func isAscii[T: char | Rune](c: T): bool =
  ord(c) < 128

The compiler generates a separate instantiation for each concrete type it's called with. It's fully statically typed and it has zero-overhead at runtime.

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 June 03, 20:09