// Scheme, in Swift. A project for cs.dorian.page's Swift tutorial, after the // Scheme interpreter in CS61A's fourth project (UC Berkeley). // // Run the tests: swift scheme.swift test // Run one problem: swift scheme.swift test 7 // Start a REPL: swift scheme.swift // Run a program: swift scheme.swift < program.scm // // Write your code between each `BEGIN PROBLEM` and `END PROBLEM` line. // Everything else is provided; read it, but do not change it. // MARK: - Provided: values /// Every value a Scheme program can compute or read. indirect enum Value { case number(Int) case boolean(Bool) case symbol(String) case null // the empty list, () case pair(Value, Value) // a list is pairs ending in .null case procedure(Procedure) /// In Scheme, every value except #f counts as true. var isTrue: Bool { if case .boolean(false) = self { return false } return true } /// The elements of a well-formed list, or an error for anything else. func toArray() throws -> [Value] { var items: [Value] = [] var current = self while case .pair(let first, let rest) = current { items.append(first) current = rest } guard case .null = current else { throw SchemeError("not a well-formed list: \(self)") } return items } } /// A Scheme list containing `values`, in order. func list(_ values: [Value]) -> Value { values.reversed().reduce(Value.null) { .pair($1, $0) } } extension Value: CustomStringConvertible { var description: String { switch self { case .number(let n): return "\(n)" case .boolean(let b): return b ? "#t" : "#f" case .symbol(let name): return name case .null: return "()" case .procedure(let procedure): return "#[\(procedure.name)]" case .pair: var parts: [String] = [] var current = self while case .pair(let first, let rest) = current { parts.append(first.description) current = rest } if case .null = current { return "(" + parts.joined(separator: " ") + ")" } return "(" + parts.joined(separator: " ") + " . \(current))" } } } /// Anything that goes wrong while reading or running a Scheme program. struct SchemeError: Error { let message: String init(_ message: String) { self.message = message } } /// The error thrown by a problem you have not solved yet. func notDone(_ problem: Int) -> SchemeError { SchemeError("Problem \(problem) is not done yet") } /// A procedure: either built into the interpreter, or created by `lambda`. final class Procedure { enum Kind { case builtin(([Value]) throws -> Value) case lambda(formals: [String], body: [Value], env: Frame) } let name: String let kind: Kind init(name: String, kind: Kind) { self.name = name self.kind = kind } } // MARK: - Problems 1 and 7: frames /// A frame binds names to values, and has a parent frame to look in when a /// name is not bound here. The global frame has no parent. final class Frame { var bindings: [String: Value] = [:] let parent: Frame? init(parent: Frame?) { self.parent = parent } // BEGIN PROBLEM 1 /// Bind `name` to `value` in this frame. func define(_ name: String, _ value: Value) { // Your code here. } /// The value of `name` in this frame or the nearest ancestor that binds /// it; throws "unknown identifier: name" if none does. func lookup(_ name: String) throws -> Value { throw notDone(1) // Replace this line. } // END PROBLEM 1 // BEGIN PROBLEM 7 /// A new frame whose parent is this one, binding each formal parameter /// to the value at the same position. Throws if the counts differ. func makeChild(formals: [String], values: [Value]) throws -> Frame { throw notDone(7) // Replace this line. } // END PROBLEM 7 } // MARK: - Provided: tokenizing /// Split source code into tokens: "(", ")", "'", and atoms. A semicolon /// starts a comment that runs to the end of the line. func tokenize(_ text: String) -> [String] { var tokens: [String] = [] var current = "" var inComment = false func finishAtom() { if !current.isEmpty { tokens.append(current) current = "" } } for character in text { if inComment { inComment = character != "\n" continue } switch character { case "(", ")", "'": finishAtom() tokens.append(String(character)) case ";": finishAtom() inComment = true case " ", "\n", "\t", "\r": finishAtom() default: current.append(character) } } finishAtom() return tokens } /// The value of a single atom: a number, #t or #f, or a symbol. func atom(_ token: String) -> Value { if let n = Int(token) { return .number(n) } switch token { case "#t", "true": return .boolean(true) case "#f", "false": return .boolean(false) default: return .symbol(token) } } // MARK: - Problem 2: reading struct Reader { let tokens: [String] var position = 0 var isAtEnd: Bool { position >= tokens.count } // BEGIN PROBLEM 2 /// Read one expression starting at `position`, and move `position` past /// it. A list becomes pairs ending in .null, and 'x becomes (quote x). mutating func read() throws -> Value { throw notDone(2) // Replace this line. } // END PROBLEM 2 } /// Every expression in `text`, in order. func readAll(_ text: String) throws -> [Value] { var reader = Reader(tokens: tokenize(text)) var expressions: [Value] = [] while !reader.isAtEnd { expressions.append(try reader.read()) } return expressions } // MARK: - Evaluation /// Evaluate `expr` in the environment `env`. func evaluate(_ expr: Value, _ env: Frame) throws -> Value { switch expr { case .number, .boolean, .null, .procedure: return expr case .symbol(let name): return try env.lookup(name) case .pair(let first, let rest): if case .symbol(let name) = first, let form = specialForm(name) { return try form(rest, env) } return try evaluateCall(first, rest, env) } } // BEGIN PROBLEM 3 /// Evaluate a call expression: evaluate the operator and then each operand, /// in order, and apply the procedure to the operands' values. func evaluateCall(_ op: Value, _ operands: Value, _ env: Frame) throws -> Value { throw notDone(3) // Replace this line. } // END PROBLEM 3 /// Apply a procedure value to argument values. func apply(_ value: Value, _ args: [Value]) throws -> Value { guard case .procedure(let procedure) = value else { throw SchemeError("not a procedure: \(value)") } switch procedure.kind { case .builtin(let function): return try function(args) case .lambda(let formals, let body, let env): return try applyLambda(formals: formals, body: body, env: env, args: args) } } // BEGIN PROBLEM 7 /// Call a user-defined procedure: bind its formals to the arguments in a new /// frame whose parent is the frame where it was defined, then evaluate its /// body there. func applyLambda(formals: [String], body: [Value], env: Frame, args: [Value]) throws -> Value { throw notDone(7) // Replace this line. } // END PROBLEM 7 // BEGIN PROBLEM 5 /// Evaluate each expression in order and return the last value. An empty /// sequence is an error. func evaluateSequence(_ expressions: [Value], _ env: Frame) throws -> Value { throw notDone(5) // Replace this line. } // END PROBLEM 5 // MARK: - Special forms typealias SpecialForm = (_ operands: Value, _ env: Frame) throws -> Value /// The special form named `name`, if there is one. func specialForm(_ name: String) -> SpecialForm? { switch name { case "define": evaluateDefine case "quote": evaluateQuote case "begin": evaluateBegin case "if": evaluateIf case "lambda": evaluateLambda case "and": evaluateAnd case "or": evaluateOr case "cond": evaluateCond case "let": evaluateLet default: nil } } /// The operands of a special form, checking how many there are. func operands(_ operands: Value, of form: String, count: ClosedRange) throws -> [Value] { let items = try operands.toArray() guard count.contains(items.count) else { throw SchemeError("wrong number of operands for \(form): \(items.count)") } return items } /// (define name value) or (define (name formals...) body...) func evaluateDefine(_ rest: Value, _ env: Frame) throws -> Value { let parts = try operands(rest, of: "define", count: 2...Int.max) switch parts[0] { case .symbol(let name): guard parts.count == 2 else { throw SchemeError("define with a name takes exactly one value") } return try defineName(name, parts[1], env) case .pair(.symbol(let name), let formals): return try defineProcedure(name, formals: formals, body: Array(parts.dropFirst()), env) default: throw SchemeError("cannot define \(parts[0])") } } // BEGIN PROBLEM 4 /// (define name value): evaluate the value, bind it, and return the name as /// a symbol. func defineName(_ name: String, _ valueExpr: Value, _ env: Frame) throws -> Value { throw notDone(4) // Replace this line. } /// (quote expr): the operand itself, not evaluated. func evaluateQuote(_ rest: Value, _ env: Frame) throws -> Value { throw notDone(4) // Replace this line. } // END PROBLEM 4 /// (begin expr...) func evaluateBegin(_ rest: Value, _ env: Frame) throws -> Value { try evaluateSequence(rest.toArray(), env) } // BEGIN PROBLEM 5 /// (if test consequent) or (if test consequent alternative). Only one branch /// is evaluated. Without an alternative, a false test gives #f. func evaluateIf(_ rest: Value, _ env: Frame) throws -> Value { throw notDone(5) // Replace this line. } // END PROBLEM 5 /// (lambda (formals...) body...) func evaluateLambda(_ rest: Value, _ env: Frame) throws -> Value { let parts = try operands(rest, of: "lambda", count: 1...Int.max) return try makeLambda(name: "lambda", formals: parts[0], body: Array(parts.dropFirst()), env) } // BEGIN PROBLEM 6 /// A procedure value for a lambda. `formals` must be a list of symbols, and /// the body must not be empty. func makeLambda(name: String, formals: Value, body: [Value], _ env: Frame) throws -> Value { throw notDone(6) // Replace this line. } // END PROBLEM 6 // BEGIN PROBLEM 8 /// (define (name formals...) body...): a procedure named `name`, bound in /// `env`. Returns the name as a symbol. func defineProcedure(_ name: String, formals: Value, body: [Value], _ env: Frame) throws -> Value { throw notDone(8) // Replace this line. } // END PROBLEM 8 // BEGIN PROBLEM 9 /// (and expr...): the first false value, or the last value, or #t if there /// are no operands. Stops evaluating at the first false value. func evaluateAnd(_ rest: Value, _ env: Frame) throws -> Value { throw notDone(9) // Replace this line. } /// (or expr...): the first true value, or #f. Stops at the first true value. func evaluateOr(_ rest: Value, _ env: Frame) throws -> Value { throw notDone(9) // Replace this line. } /// (cond (test body...)... (else body...)): the body of the first clause /// whose test is true, or the test's value if the body is empty; #f if no /// clause is true. func evaluateCond(_ rest: Value, _ env: Frame) throws -> Value { throw notDone(9) // Replace this line. } // END PROBLEM 9 // BEGIN PROBLEM 10 /// (let ((name value)...) body...): evaluate every value in `env`, bind /// them in a new child frame, and evaluate the body there. func evaluateLet(_ rest: Value, _ env: Frame) throws -> Value { throw notDone(10) // Replace this line. } // END PROBLEM 10 // MARK: - Problem 11: Scheme programs // BEGIN PROBLEM 11 /// Scheme code, run in the global frame before Problem 11's tests. let schemePrograms = """ ; (enumerate s): a list of (index element) lists, counting from 0. (define (enumerate s) 'replace-this-line) ; (merge ordered? s1 s2): merge two lists already sorted by ordered?. (define (merge ordered? s1 s2) 'replace-this-line) """ // END PROBLEM 11 // MARK: - Provided: built-in procedures func numbers(_ args: [Value], _ name: String) throws -> [Int] { try args.map { arg in guard case .number(let n) = arg else { throw SchemeError("\(name) expects numbers, not \(arg)") } return n } } func arity(_ args: [Value], _ name: String, _ count: Int) throws { guard args.count == count else { throw SchemeError("\(name) takes \(count) arguments, got \(args.count)") } } func isEqual(_ a: Value, _ b: Value) -> Bool { switch (a, b) { case let (.number(x), .number(y)): x == y case let (.boolean(x), .boolean(y)): x == y case let (.symbol(x), .symbol(y)): x == y case (.null, .null): true case let (.pair(a1, a2), .pair(b1, b2)): isEqual(a1, b1) && isEqual(a2, b2) case let (.procedure(x), .procedure(y)): x === y default: false } } /// A new global frame containing the built-in procedures. func makeGlobalFrame() -> Frame { let global = Frame(parent: nil) func builtin(_ name: String, _ function: @escaping ([Value]) throws -> Value) { global.define(name, .procedure(Procedure(name: name, kind: .builtin(function)))) } func compare(_ name: String, _ test: @escaping (Int, Int) -> Bool) { builtin(name) { args in let ns = try numbers(args, name) return .boolean(zip(ns, ns.dropFirst()).allSatisfy(test)) } } func check(_ name: String, _ test: @escaping (Value) -> Bool) { builtin(name) { args in try arity(args, name, 1) return .boolean(test(args[0])) } } builtin("+") { .number(try numbers($0, "+").reduce(0, +)) } builtin("*") { .number(try numbers($0, "*").reduce(1, *)) } builtin("-") { args in let ns = try numbers(args, "-") guard let first = ns.first else { throw SchemeError("- needs at least one argument") } return .number(ns.count == 1 ? -first : ns.dropFirst().reduce(first, -)) } for (name, op) in [("quotient", { (a: Int, b: Int) in a / b }), ("remainder", { $0 % $1 }), ("modulo", { (($0 % $1) + $1) % $1 })] { builtin(name) { args in try arity(args, name, 2) let ns = try numbers(args, name) guard ns[1] != 0 else { throw SchemeError("division by zero") } return .number(op(ns[0], ns[1])) } } builtin("abs") { args in try arity(args, "abs", 1) return .number(abs(try numbers(args, "abs")[0])) } compare("=", ==) compare("<", <) compare(">", >) compare("<=", <=) compare(">=", >=) builtin("not") { args in try arity(args, "not", 1) return .boolean(!args[0].isTrue) } builtin("cons") { args in try arity(args, "cons", 2) return .pair(args[0], args[1]) } builtin("car") { args in try arity(args, "car", 1) guard case .pair(let first, _) = args[0] else { throw SchemeError("car of \(args[0])") } return first } builtin("cdr") { args in try arity(args, "cdr", 1) guard case .pair(_, let rest) = args[0] else { throw SchemeError("cdr of \(args[0])") } return rest } builtin("list") { list($0) } builtin("length") { args in try arity(args, "length", 1) return .number(try args[0].toArray().count) } builtin("append") { args in list(try args.flatMap { try $0.toArray() }) } builtin("equal?") { args in try arity(args, "equal?", 2) return .boolean(isEqual(args[0], args[1])) } check("null?") { if case .null = $0 { true } else { false } } check("pair?") { if case .pair = $0 { true } else { false } } check("number?") { if case .number = $0 { true } else { false } } check("symbol?") { if case .symbol = $0 { true } else { false } } check("procedure?") { if case .procedure = $0 { true } else { false } } check("even?") { if case .number(let n) = $0 { n % 2 == 0 } else { false } } check("odd?") { if case .number(let n) = $0 { n % 2 != 0 } else { false } } return global } // MARK: - Provided: running programs /// Run a whole program in `env` and describe the last value, or the error. func run(_ program: String, in env: Frame = makeGlobalFrame()) -> String { do { var last = "" for expression in try readAll(program) { last = try evaluate(expression, env).description } return last } catch let error as SchemeError { return "Error: \(error.message)" } catch { return "Error: \(error)" } } /// Read, evaluate, and print, until the end of input. func repl() { let env = makeGlobalFrame() var buffer = "" print("scm> ", terminator: "") while let line = readLine() { buffer += line + "\n" let depth = tokenize(buffer).reduce(0) { $0 + ($1 == "(" ? 1 : $1 == ")" ? -1 : 0) } if depth > 0 { print("...> ", terminator: "") continue } do { for expression in try readAll(buffer) { print(try evaluate(expression, env)) } } catch let error as SchemeError { print("Error: \(error.message)") } catch { print("Error: \(error)") } buffer = "" print("scm> ", terminator: "") } print() } // MARK: - Tests (do not edit below this line) var onlyProblem: Int? = nil var passed = 0 var failed = 0 var failedProblems = Set() func check(_ problem: Int, _ description: String, _ actual: @autoclosure () -> T, _ expected: T) { if let only = onlyProblem, only != problem { return } let value = actual() if value == expected { passed += 1 } else { failed += 1 failedProblems.insert(problem) print("✗ Problem \(problem): \(description)") print(" expected \(expected), got \(value)") } } /// Whether a program fails with a real error (not "Problem N is not done"). func fails(_ program: String) -> String { let result = run(program) if result.contains("is not done yet") { return result } return result.hasPrefix("Error") ? "an error" : result } func lookupText(_ frame: Frame, _ name: String) -> String { do { return try frame.lookup(name).description } catch let error as SchemeError { return error.message.contains("is not done yet") ? error.message : "an error" } catch { return "\(error)" } } func readText(_ text: String) -> String { do { return try readAll(text).map(\.description).joined(separator: " | ") } catch let error as SchemeError { return error.message.contains("is not done yet") ? error.message : "an error" } catch { return "\(error)" } } func runTests() { // Problem 1: frames let global = Frame(parent: nil) global.define("x", .number(3)) global.define("y", .boolean(true)) let child = Frame(parent: global) child.define("x", .number(10)) child.define("z", .symbol("zebra")) check(1, "lookup in the same frame", lookupText(global, "x"), "3") check(1, "a child's binding shadows its parent's", lookupText(child, "x"), "10") check(1, "lookup continues in the parent", lookupText(child, "y"), "#t") check(1, "a parent cannot see its child", lookupText(global, "z"), "an error") check(1, "unknown names are errors", lookupText(child, "w"), "an error") global.define("x", .number(4)) check(1, "define replaces a binding", lookupText(global, "x"), "4") // Problem 2: reading check(2, "a number", readText("42"), "42") check(2, "a flat list", readText("(+ 1 2)"), "(+ 1 2)") check(2, "nested lists", readText("(1 (2 (3)) () 4)"), "(1 (2 (3)) () 4)") check(2, "booleans and symbols", readText("(#t #f hello)"), "(#t #f hello)") check(2, "quote shorthand", readText("'x"), "(quote x)") check(2, "quoted list", readText("'(1 '2)"), "(quote (1 (quote 2)))") check(2, "several expressions", readText("1 (a) ; a comment\n b"), "1 | (a) | b") check(2, "a missing )", readText("(1 (2 3)"), "an error") check(2, "an unexpected )", readText(")"), "an error") check(2, "reading builds pairs", { var reader = Reader(tokens: tokenize("(1 2)")) guard let value = try? reader.read(), case .pair(.number(1), .pair(.number(2), .null)) = value else { return false } return reader.isAtEnd }(), true) // Problem 3: call expressions check(3, "a simple call", run("(+ 1 2)"), "3") check(3, "nested calls", run("(* (+ 1 2) (- 10 4))"), "18") check(3, "calls with lists", run("(car (cdr (list 1 2 3)))"), "2") check(3, "no operands", run("(+)"), "0") check(3, "the operator is evaluated too", run("((car (list + *)) 3 4)"), "7") check(3, "calling a number", fails("(1 2)"), "an error") check(3, "an unknown name in an operand", fails("(+ 1 undefined-name)"), "an error") // Problem 4: define and quote check(4, "define returns the name", run("(define x 2)"), "x") check(4, "defined names can be used", run("(define x 5) (* x x)"), "25") check(4, "the value is evaluated first", run("(define y (+ 1 2)) (define z (* y y)) z"), "9") check(4, "quote", run("(quote (a b))"), "(a b)") check(4, "quote shorthand", run("'hello"), "hello") check(4, "quoted code is not run", run("'(+ 1 2)"), "(+ 1 2)") check(4, "quote takes one operand", fails("(quote a b)"), "an error") // Problem 5: begin and if check(5, "begin returns the last value", run("(begin 1 2 3)"), "3") check(5, "begin runs everything", run("(begin (define a 4) (* a a))"), "16") check(5, "empty begin", fails("(begin)"), "an error") check(5, "if chooses a branch", run("(if (< 1 2) (+ 1 1) 0)"), "2") check(5, "only one branch is evaluated", run("(if #t 1 (quotient 1 0))"), "1") check(5, "0 is true in Scheme", run("(if 0 'yes 'no)"), "yes") check(5, "if without an alternative", run("(if #f 1)"), "#f") // Problem 6: lambda check(6, "lambda makes a procedure", run("(lambda (x) (* x x))"), "#[lambda]") check(6, "procedures are values", run("(procedure? (lambda () 1))"), "#t") check(6, "formals must be symbols", fails("(lambda (x 1) x)"), "an error") check(6, "a body is required", fails("(lambda (x))"), "an error") // Problem 7: calling user-defined procedures check(7, "call a lambda directly", run("((lambda (x y) (+ x y)) 3 4)"), "7") check(7, "call a named lambda", run("(define square (lambda (x) (* x x))) (square 5)"), "25") check(7, "the body can have several expressions", run("((lambda (x) (define y 2) (* x y)) 21)"), "42") check(7, "recursion", run("(define fact (lambda (n) (if (= n 0) 1 (* n (fact (- n 1)))))) (fact 10)"), "3628800") check(7, "closures", run(""" (define make-adder (lambda (n) (lambda (x) (+ x n)))) (define add3 (make-adder 3)) (add3 4) """), "7") check(7, "lexical scope", run(""" (define x 1) (define f (lambda () x)) (define g (lambda (x) (f))) (g 2) """), "1") check(7, "a call does not change its caller's frame", run("(define x 1) ((lambda (x) x) 2) x"), "1") check(7, "too many arguments", fails("((lambda (x) x) 1 2)"), "an error") // Problem 8: define shorthand check(8, "define a procedure", run("(define (square x) (* x x)) (square 6)"), "36") check(8, "define returns the name", run("(define (f) 1)"), "f") check(8, "the procedure knows its name", run("(define (sq x) (* x x)) sq"), "#[sq]") check(8, "a body with several expressions", run("(define (f x) (define y (* x 2)) (+ y 1)) (f 5)"), "11") check(8, "tree recursion", run("(define (fib n) (if (< n 2) n (+ (fib (- n 2)) (fib (- n 1))))) (fib 15)"), "610") check(8, "higher-order procedures", run(""" (define (compose f g) (lambda (x) (f (g x)))) (define (inc x) (+ x 1)) ((compose inc inc) 5) """), "7") // Problem 9: and, or, cond check(9, "empty and", run("(and)"), "#t") check(9, "and returns the last value", run("(and 1 2 3)"), "3") check(9, "and stops at the first false value", run("(and 1 #f (quotient 1 0))"), "#f") check(9, "empty or", run("(or)"), "#f") check(9, "or stops at the first true value", run("(or #f 5 (quotient 1 0))"), "5") check(9, "or returns #f when nothing is true", run("(or #f #f)"), "#f") check(9, "the first true clause", run("(cond ((= 1 2) 'a) ((= 1 1) 'b) (else 'c))"), "b") check(9, "else", run("(cond (#f 'a) (else 'c))"), "c") check(9, "no true clause", run("(cond (#f 1))"), "#f") check(9, "a clause with no body", run("(cond ((+ 1 1)))"), "2") check(9, "later clauses are not evaluated", run("(cond (#t 1) ((quotient 1 0) 2))"), "1") check(9, "a body with several expressions", run("(cond (#t (define z 3) (* z z)))"), "9") // Problem 10: let check(10, "let binds names", run("(let ((x 2) (y 3)) (* x y))"), "6") check(10, "values are evaluated outside the let", run("(define x 1) (let ((x 10) (y x)) (+ x y))"), "11") check(10, "bindings do not leak", run("(define x 1) (let ((x 2)) x) x"), "1") check(10, "a body with several expressions", run("(let ((x 1)) (define y 5) (+ x y))"), "6") check(10, "a bad binding", fails("(let ((x)) x)"), "an error") // Problem 11: Scheme programs check(11, "enumerate", run(schemePrograms + "(enumerate '(a b c))"), "((0 a) (1 b) (2 c))") check(11, "enumerate an empty list", run(schemePrograms + "(enumerate '())"), "()") check(11, "merge ascending", run(schemePrograms + "(merge < '(1 5 7 9) '(4 8 10))"), "(1 4 5 7 8 9 10)") check(11, "merge descending", run(schemePrograms + "(merge > '(9 5 1) '(8 3))"), "(9 8 5 3 1)") check(11, "merge with an empty list", run(schemePrograms + "(merge < '() '(2))"), "(2)") let total = passed + failed if failed == 0 && total > 0 { print("\(total) of \(total) checks passed.") print(onlyProblem.map { "Problem \($0) passed." } ?? "All tests passed.") } else { print("\(passed) of \(total) checks passed. Problems to revisit: \(failedProblems.sorted()).") } } let arguments = Array(CommandLine.arguments.dropFirst()) switch arguments.first { case "test": onlyProblem = arguments.dropFirst().first.flatMap { Int($0) } runTests() case nil: repl() default: print("Usage: swift scheme.swift test [problem] | swift scheme.swift") }