Colors
examples/colors.sld:
;; Structs, enums, typeclasses and pattern matching.
(import
(snail core base)
(snail core io))
(record (Vec3 T)
((x T)
(y T)
(z T)))
(enum PrimaryColor
(Red)
(Green)
(Blue))
(enum Color
(Primary ((value PrimaryColor)))
(Rgb ((value (Vec3 I64)))))
(typeclass (ToHex T)
(declare (to-hex (value T)) (→ String)))
(define (channel-hex (value I64)) (→ String)
(let ((digits "0123456789abcdef"))
(string (string-ref digits (quotient value 16)) (string-ref digits (remainder value 16)))))
(instance (ToHex PrimaryColor)
(define (to-hex (color PrimaryColor)) (→ String)
(match color
((Red) "#ff0000")
((Green) "#00ff00")
((Blue) "#0000ff"))))
(instance (ToHex (Vec3 I64))
(define (to-hex (v (Vec3 I64))) (→ String)
(string-append "#" (channel-hex (● v x)) (channel-hex (● v y)) (channel-hex (● v z)))))
(instance (ToHex Color)
(define (to-hex (color Color)) (→ String)
(match color
((Primary value) (to-hex value))
((Rgb value) (to-hex value)))))
(define (main (out OutputPort)) (→ Unit)
(for-each (lambda (color) (write-line out (to-hex color)))
(list (Primary (Red)) (Rgb (new Vec3 (x 255) (y 160) (z 0))) (Primary (Blue))))
(unit))
It prints:
#ff0000
#ffa000
#0000ff