calog/examples/scripts/languages/scheme.scm

36 lines
1.3 KiB
Scheme

; A guided tour of s7 Scheme running on calog.
; Demonstrates: a recursive factorial, a list built and mapped over, string
; assembly, and the cryptoHashSha256 native -- all inside ONE (begin ...) form,
; because s7's runSource reads a single top-level form per script.
; Run: bin/calog examples/scripts/languages/scheme.scm
(begin
; A classic recursive function.
(define (factorial n)
(if (<= n 1)
1
(* n (factorial (- n 1)))))
; Build a list, then derive a second list by mapping factorial over it.
(define nums (list 1 2 3 4 5 6))
(define facts (map factorial nums))
; object->string turns an aggregate into a readable literal for printing
; (calogPrint renders a raw list as "[aggregate]").
(calogPrint "nums =" (object->string nums))
(calogPrint "facts =" (object->string facts))
; Fold the mapped list into a running sum with a tail-recursive helper.
(define (sum-list lst acc)
(if (null? lst)
acc
(sum-list (cdr lst) (+ acc (car lst)))))
(calogPrint "sum of factorials =" (sum-list facts 0))
; Hash a message with the crypto native; it returns a lowercase hex digest.
(define message "calog + s7 scheme")
(calogPrint "sha256(" message ") =" (cryptoHashSha256 message))
; Tear down and exit cleanly (required -- calog does not auto-exit).
(calogExit 0))