|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching • Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
Check if a text is ASCII onlyWe 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. |
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |