Skip to content

More examples #12

@vks

Description

@vks

I don't know what kind of example you want in the examples directory, but here are a few simple programs:

Tower of Hanoi

(define (move n from to via)
    (cond ((< n 1)
           (panic "expected integer larger than 0"))
          ((= n 1)
           (println "Move disk ~a from ~a to ~a." n from to))
          (else
           (do
            (move (- n 1) from via to)
            (println "Move disk ~a from ~a to ~a." n from to)
            (move (- n 1) via to from)))))

(move 3 "L" "M" "R")

FizzBuzz

(define (fizzbuzz a b)
  (if (<= a b)
    (do
      (let ((divisible-by-3 (= (rem a 3) 0))
            (divisible-by-5 (= (rem a 5) 0)))
        (cond
          ((and divisible-by-3 divisible-by-5)
            (println "FizzBuzz"))
          (divisible-by-3
            (println "Fizz"))
          (divisible-by-5
            (println "Buzz"))
          (else
            (println "~a" a))))
      (fizzbuzz (+ a 1) b))))

(fizzbuzz 1 100)

Extensible FizzBuzz

(use list (map))

(define (is-divisible a b) (= (rem a b) 0))

(define tags '((3 "Fizz") (5 "Buzz")))

(define (evaluate i)
  (let ((find-desc (lambda (tag)
          (if (is-divisible i (first tag)) (last tag) "")))
        (desc (format "~{~a~}" (map find-desc tags))))
    (if (= desc "") (format "~a" i) desc)))

(define (fizzbuzz start end)
  (if (<= start end) (do
    (println "~a" (evaluate start))
    (fizzbuzz (+ 1 start) end))))

(fizzbuzz 1 100)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions