Skip to content

HW 9: Raskell

In Lab 9, you met Raskell, a small Racket-like language whose interpreter is written in Haskell, and you added one list operation to it. Right now Raskell can quote data, make and call functions, and take lists apart, and that's about all. In this assignment you turn it into a language you can actually program in. You add, in order:

  • arithmetic, comparisons, and conditionals
  • local bindings
  • list operations that take functions as arguments

Then you stop writing Haskell and write the rest of the language's list library, and finally a real program, in Raskell itself.

That program is an old friend: the Collatz (3n + 1) sequence.

You've done this before

This is the third time you've met Collatz. In HW 2, you wrote step and countStep in Haskell. In HW 8, you wrote Step and Tnpo in the lambda calculus, with nothing but functions. This time you write it in a language you implemented. Both of those earlier solutions are worth a look before Stage 6.

The interpreter will feel familiar too. The environments, closures, and let of Module 5 are all here, now for a language with S-expression syntax.

How you'll get materials and submit this assignment

Getting the starter code and turning in your work follows the same process as every homework this semester. See The Homework Workflow for the full walkthrough. In short:

  1. From the hw9 template repo, make your own private copy.
  2. Clone it to the course server.
  3. Submit on Gradescope:
    • your test output
    • your code
    • a few short written answers

The rest of this page covers what the assignment actually asks of you.

What You'll Do

  • Add primitive operations to an interpreter: arithmetic and comparisons on integers.
  • Add special forms that decide which of their arguments get evaluated: if, cond, and, and or.
  • Implement let by translating it into something the interpreter already understands.
  • Write map and foldl, primitives that call functions written in the language being interpreted.
  • Write library functions in Raskell, and see how that differs from adding them to the interpreter.
  • Write a complete program in the language you built.

Checklist

  • Get the assignment materials (see The Homework Workflow)
  • Stage 1: +, -, *, quotient, modulo, =, <, >, <=, >=
  • Stage 2: not, if, cond, and, or
  • Stage 3: let, and letrec (write it yourself, or copy the solution)
  • Stage 4: list, append, map, foldl
  • Stage 5: reverse and filter, in Raskell
  • Stage 6: programs/collatz.rask
  • Turn in the assignment (see Turning It In)

Collaboration

You can work with a partner on this assignment. If you do, you must cooperate on every part, follow the pair-programming rules from the syllabus at all times, and share roles equally.


The Files

File What it is
RaskEval.hs The Haskell file you edit. The evaluator: special forms, function application, and primitives. Everything you need to fill in is marked TODO (Stage N).
rasklib/list-library.rask You edit this (Stage 5). Raskell's list library, written in Raskell.
programs/collatz.rask You edit this (Stage 6). Your Collatz program.
RaskAST.hs PROVIDED. The SExpr and Value datatypes, and printing. You'll read it often. You shouldn't need to change it.
RaskParser.hs, Rask.hs PROVIDED. The parser, and the REPL and file runner.
ParserCombinators.hs, ParserBase.hs PROVIDED: DO NOT EDIT. The course's parser-combinator library, the same one you used for piq. You do not need to understand how these files are implemented.
rask, run-tests PROVIDED. Run Raskell (compiling it when needed), and run the tests.
tests/ PROVIDED: DO NOT EDIT. The tests, one small .rask file each, in a folder per stage.
programs/swap.rask, programs/square.rask PROVIDED. Two small sample programs, to show what a Raskell program file looks like.
programs/library-demo.rask PROVIDED. A sample program that uses your list library (Stage 5).

The starter already has everything from Lab 9, including rest. It also has one new primitive, empty?, which tells you whether a list is empty: (empty? '()) is #t, and (empty? '(a b)) is #f. Its RaskEval.hs is a little longer than the lab's. It has placeholders for every feature you'll add, including letrec (Stage 3 explains it). Each placeholder gives the error not implemented yet.


How to Work

Running Raskell

./rask                          # the REPL (:q to quit)
./rask --file program.rask      # run the program in a file

./rask recompiles the interpreter whenever a .hs file has changed. If your Haskell has a type error, GHC's message appears when you run ./rask or ./run-tests.

A program in a file is one S-expression, which can span many lines. A ; starts a comment that runs to the end of the line.

Two small samples in programs/ show the format. swap.rask works with the starter right away:

./rask --file programs/swap.rask             # (world hello)

square.rask's value is a function. When a program's value is a function, the file runner applies it to each number on the command line. It uses *, so it works with your interpreter once you finish Stage 1. You can try it now with rask-reference:

rask-reference --file programs/square.rask 3 12    # 9, then 144

Tests

./run-tests                     # all the tests
./run-tests 02                  # just Stage 2 (the folder tests/02-control)

Each stage has a folder of tests, numbered to match the stages on this page (tests/00-baseline checks the features you start with).

  • A test is a small .rask file whose first line says what output it expects.
  • A test that expects error passes for any Raskell error message except not implemented yet.
  • When a test fails, run-tests shows:
    • the program
    • what it expected
    • what it got
  • The summary at the end gives a count for each stage.

The stages are independent, so you can finish them in order and watch each one fill in. (Stages 5 and 6 need Stages 1 to 4, because your Raskell code uses those features.)

The reference interpreter

The course server has a finished Raskell interpreter called rask-reference. It takes the same arguments as ./rask:

rask-reference                              # its REPL
rask-reference --file program.rask          # run a file with it
./run-tests --reference                     # run the tests with it, instead of your code
./run-tests --reference 05                  # ...just Stage 5

Use it to answer "what should this do?" Whenever your interpreter does something that surprises you, run the same expression through rask-reference.

  • If the two differ, the bug is in your Haskell.
  • If they agree, the surprise is in your understanding of the language, or in your Raskell program.

(One expected difference: rask-reference's error messages may be worded differently from yours. Any error counts as matching any other error.)

That makes it especially handy in Stages 5 and 6. With --reference, you can test your Raskell library and your Collatz program before your interpreter is finished, and you know any failure is in your Raskell code.

Racket is here too

racket is also installed on the server, and Raskell is close to a subset of it, so Racket is a good second opinion for most expressions. A few differences are listed in the next section. Racket prints a quote in front of a list result ('(1 2)), and Raskell doesn't ((1 2)).


The Language

These are the rules for the finished language. The tests check them, and rask-reference follows them.

Values. Raskell has five kinds of values:

  • integers
  • the Booleans #t and #f
  • symbols
  • lists
  • functions

The empty list (), the Boolean #f, and an error are three different things. Unlike some Lisps, Raskell never treats one as another.

Printing.

  • A list prints in parentheses, as in (1 (a b) #t).
  • A symbol prints as its name.
  • A function prints as #<procedure>, or #<procedure:+> for a primitive.
  • An error prints as error: followed by a message.

Function calls.

  • For a call (f a b ...), Raskell evaluates f and every argument first (call by value), then applies the function.
  • A function made with lambda must receive exactly as many arguments as it has parameters.
  • Scope is lexical.

Truth. These accept only Booleans as tests:

  • if
  • cond
  • and
  • or
  • not

Using anything else, such as (if 0 'a 'b), is an error. (Racket would treat 0 as true. Raskell is stricter.)

Arity.

  • These take exactly two numbers:
    • +, -, and *
    • quotient and modulo
    • the comparisons =, <, >, <=, and >=
  • append takes exactly two lists.
  • and and or take any number of arguments, including none.

(Racket allows more. Raskell keeps it simple.)


Stage 0: Look Around

Before you change anything, run ./run-tests. The 23 tests in 00-baseline should pass, and almost everything else should fail.

There's nothing to implement in this stage. Open RaskEval.hs and find your way around. You saw some of it in the lab. Find these parts:

  • eval, with one equation for each kind of expression:
    • Special forms, each listed by name:
      • quote
      • lambda
      • if
      • cond
      • and
      • or
      • let
      • letrec
    • Any other list is an application.
  • apply, which calls a function value, whether it's a primitive (VPrim) or a closure (VClosure).
  • The primitives table, which lists every primitive by its Raskell name. It's how names like cons and + get their meaning: initEnv binds each name to its primitive.

Write only the case that makes sense. The provided primitives are your models. Each one is a single equation whose pattern describes the arguments it expects:

primCons :: [Value] -> Value
primCons [x, VList xs] = VList (x : xs)      -- exactly two arguments, the second a list

primRest :: [Value] -> Value
primRest [VList (_ : rest)] = VList rest     -- exactly one argument, a nonempty list

primEmpty :: [Value] -> Value
primEmpty [VList xs] = VBool (null xs)       -- exactly one argument, any list

You never write code for the wrong cases. A program like (cons 1 2) or (rest '()) doesn't fit the pattern, so no equation matches. Haskell stops, and Raskell prints an error such as error: Non-exhaustive patterns in function primRest. The same goes for a case with no matching alternative. Every rule in The Language above that says "is an error" works this way: if your patterns describe only the correct shapes, the errors happen on their own.

Better error messages are an optional extra

Once everything works and you've submitted, you're welcome to go back and add better error handling, with clearer messages like the ones rask-reference prints. It isn't required, and it doesn't change your grade. The tests accept any error message, so they keep passing.


Stage 1: Arithmetic and Comparisons

Expression Result
(+ 3 5) 8
(- 3 10) -7
(* 4 6) 24
(quotient 10 3) 3
(modulo 10 3) 1
(<= 4 4) #t
(+ 1 'a) an error
(quotient 1 0) an error

Look at the primitives table. The entry for + is

("+", arith (+))

That's a partial application: arith takes a Haskell function on Integers, and then the list of argument values. So (+ 3 5) runs arith (+) [VNumber 3, VNumber 5]. - and * use arith too, so writing arith once gives you all three. The comparisons share compareWith the same way.

Implement: arith, compareWith, primQuotient, primModulo

In RaskEval.hs, replace each placeholder marked TODO (Stage 1):

  • arith
  • compareWith
  • primQuotient
  • primModulo

Each is one equation, like primCons. Its pattern says "exactly two arguments, both numbers", and gives the two Integers names. Then (+ 1 'a) and (+ 1 2 3) are errors automatically.

Integer division. As in Racket, quotient rounds toward zero, so (quotient -7 2) is -3. modulo gives a result with the sign of the divisor, so (modulo -7 2) is 1. Haskell has a function for each: look up quot and mod. Dividing by zero is a Raskell error, and you get it for free: Haskell's quot and mod stop with divide by zero, and Raskell prints that as error: divide by zero.

✅ Check your work (Stage 1)

./run-tests 01 should pass all 24 tests.

Then try your arithmetic by hand. Start the REPL with ./rask, type each expression at the raskell> prompt, and check that you get the result in the comment. Type :q to quit.

Simple operations:

(+ 3 5)                    ; 8
(- 3 10)                   ; -7
(= (+ 2 2) 4)              ; #t

Nested expressions. The arguments are evaluated first, so the inner calls run before the outer one:

(* (+ 1 2) (- 10 4))          ; 18
(quotient (* 7 6) (- 10 3))   ; 6
(< (* 2 3) (+ 2 3))           ; #f

Integer division with negative numbers. These are the two rules from above:

(quotient -7 2)            ; -3
(modulo -7 2)              ; 1

Arithmetic inside a lambda:

((lambda (x) (* x x)) 9)                    ; 81
((lambda (x y) (+ (* x x) (* y y))) 3 4)    ; 25

A primitive passed as an argument. A primitive is a value like any other, so you can pass it to a function. Here the lambda calls whatever operation it's given:

((lambda (op) (op 2 3)) *)   ; 6
((lambda (op) (op 2 3)) -)   ; -1
((lambda (op) (op 2 3)) <)   ; #t
+                            ; #<procedure:+>

Errors. Each of these should print some error: message. The exact text doesn't matter.

(+ 1 'a)                   ; not a number
(+ 1 2 3)                  ; too many arguments
(quotient 1 0)             ; divide by zero

If any result surprises you, try the same expression in rask-reference.

Think about it

Adding arithmetic didn't change eval at all. Why not? What did change, so that the symbol + in a program came to mean addition?


Stage 2: Booleans and Controlled Evaluation

Expression Result
(not #f) #t
(if (< 1 2) 'yes 'no) yes
(if #t 7 (quotient 1 0)) 7, with no error
(and #f (= 1 (quotient 1 0))) #f, with no error
(or #t (= 1 (quotient 1 0))) #t, with no error
(and) / (or) #t / #f
(cond ((= 1 2) 'a) ((= 1 1) 'b) (else 'c)) b

not is an ordinary primitive, like the ones in Stage 1. The other four are special forms, and that's the point of this stage. A function call evaluates all its arguments before the function runs. if can't work that way: (if #t 7 (quotient 1 0)) must give 7, so if must never evaluate the branch it doesn't choose. The same goes for and, or, and cond. Each receives its arguments as unevaluated SExprs, and it decides which ones to evaluate, and when.

Implement: primNot, evalIf, evalAnd, evalOr, evalCond

In RaskEval.hs, replace each placeholder marked TODO (Stage 2):

Function Implements Kind
primNot not a primitive, like the ones in Stage 1
evalIf if a special form
evalAnd and a special form
evalOr or a special form
evalCond cond a special form

Do cond last. It's the longest of the four special forms, and it has its own section below.

eval already sends each special form to its function. For example, (if test a b) becomes evalIf env [test, a, b]. Each function gets the current environment and the form's arguments, as a list of SExprs, without the keyword.

  • if (evalIf) has exactly three arguments:

    • a test
    • a then-branch
    • an else-branch

    Evaluate the test, then evaluate only the chosen branch. Use a case on the test's value with two alternatives, VBool True and VBool False. Any other value, as in (if 0 'a 'b), matches neither, so it's an error automatically.

  • and (evalAnd) and or (evalOr) take any number of arguments, and evaluate them left to right:

    • and stops at the first #f.
    • or stops at the first #t.
    • With no arguments, (and) is #t and (or) is #f.

    Like if, they accept only Booleans, so use the same kind of case.

cond (evalCond)

A cond is a list of clauses. Each clause is a two-element list (test result), and the last one may be (else result):

(cond ((< n 0) 'negative)
      ((= n 0) 'zero)
      (else    'positive))

Here's how it's evaluated:

  • The clauses are tried in order.
  • The result of the first clause whose test is #t is the answer, and later clauses aren't evaluated at all.
  • An optional last clause (else result) matches anything.
  • If no clause matches, it's an error.

What evalCond receives. For (cond ((= 1 2) 'a) (else 'c)), eval calls evalCond env parts, where parts is this list of two clauses:

[ SList [SList [SSymbol "=", SNumber 1, SNumber 2], SList [SSymbol "quote", SSymbol "a"]]
, SList [SSymbol "else", SList [SSymbol "quote", SSymbol "c"]]
]

Notice three things:

  • Each clause is an SList of exactly two SExprs, the test and the result.
  • 'a has already become (quote a). The parser does that for every '.
  • else is just a symbol, SSymbol "else". The parser doesn't treat it specially. Only your evalCond does.

The two equations. Write them in this order:

  1. evalCond env [SList [SSymbol "else", result]], for a final else clause. An else always matches, so what's the answer?
  2. evalCond env (SList [test, result] : clauses), for a (test result) clause followed by the rest of the clauses. Evaluate test, and handle the two Booleans it can give, the same way you did in evalIf:
    • If it's #t, this clause wins. What do you evaluate?
    • If it's #f, this clause is skipped, and the answer comes from the remaining clauses. Which function already knows how to handle a list of clauses?

With no clauses left, nothing matches, which is the error.

The else equation must come first

An else clause also fits the second pattern, with SSymbol "else" as the test. Haskell tries equations from top to bottom. If the general equation came first, it would evaluate else as a variable, and (cond (#f 'a) (else 'z)) would give error: unbound identifier: else. When it compiles that order, GHC warns Pattern match has inaccessible right hand side, pointing at the else equation.

✅ Check your work (Stage 2)

./run-tests 02 should pass all 28 tests. The ones with short-circuit in their names check that you don't evaluate too much.


Stage 3: Local Bindings

let

A let gives names to some values, for use in one expression, its body:

(let ((name1 expr1)
      (name2 expr2))
  body)

It has two arguments:

  • a list of bindings, each a two-element list (name expr)
  • the body, a single expression

Some examples:

(let ((x 10)) (+ x 5))                    ; 15
(let ((x 2) (y 3)) (* x y))               ; 6
(let ((x 1)) (let ((x 2) (y x)) y))       ; 1

Here's how a let is evaluated:

  1. Evaluate each expr in the current environment, the one the let appears in.
  2. Make a new environment: the current one, plus each name bound to its value.
  3. Evaluate the body in that new environment. Its value is the value of the whole let.

All the expressions are evaluated in step 1, before any of the new names exist in step 2. So a binding can't use another name from the same let:

(let ((x 2) (y x)) y)                     ; error: unbound identifier: x

Tracing the last example. Here's how (let ((x 1)) (let ((x 2) (y x)) y)) gives 1:

  • The outer let evaluates 1, then evaluates its body in an environment where x is 1.
  • That body is the inner let. It evaluates its two expressions in that same environment, where x is still 1:
    • 2 gives 2.
    • x gives 1. The inner x doesn't exist yet.
  • The inner let evaluates its body, y, in a new environment where x is 2 and y is 1. So the answer is 1.

The inner x shadows the outer one, but only inside the inner let's body, not in its binding expressions.

(Racket also has let*, which binds the names one at a time, so a later binding can use an earlier one. Raskell has only let.)

You've seen this before. In Module 5, let turned out to mean the same thing as applying a function:

(let ((x 10) (y 20)) body)      means      ((lambda (x y) body) 10 20)

Implement: evalLet

In RaskEval.hs, replace the placeholder marked TODO (Stage 3).

Build the application ((lambda (name1 name2 ...) body) expr1 expr2 ...) as an SExpr, and eval it. Don't write new code for environments. The lambda and application code you already have does all of that.

How to build it:

  • A let has two parts, the binding list and the body, so the pattern is evalLet env [SList bindings, body].
  • Each binding is an SList of two things:
    • a name
    • an expression
  • Use map to collect the names into one list, and again to collect the expressions into another.
  • Build the application of a lambda to the expressions, and eval it.

letrec (an optional challenge)

Try this in the REPL once let works:

(let ((down (lambda (n) (if (= n 0) '() (cons n (down (- n 1))))))) (down 3))

It fails with unbound identifier: down. The lambda is evaluated in the environment outside the let, where down isn't bound yet, so the closure doesn't know its own name. That's lexical scope doing exactly what it should, and it means let can't define a recursive function.

letrec can:

(letrec ((down (lambda (n) (if (= n 0) '() (cons n (down (- n 1)))))))
  (down 3))                               ; (3 2 1)

(letrec ((fact (lambda (n) (if (= n 0) 1 (* n (fact (- n 1)))))))
  (fact 5))                               ; 120

Here's how Raskell's letrec behaves:

  • It binds exactly one name, to a lambda.
  • Inside that lambda's body, the name refers to the function itself, so the function can call itself.
  • The letrec's own body runs with the name bound, too.
  • Anything else, such as two bindings or a name bound to something that isn't a lambda, is an error.

Implement (optional challenge): evalLetrec

In RaskEval.hs, replace the placeholder marked TODO (Stage 3, optional challenge).

You can write it yourself or copy the solution from How letrec Works. Either way is fine, and it doesn't affect your grade. But you do need a working letrec, for two of the Stage 3 tests and for Stage 6.

Here's the pattern for it. Matching the shape is tedious, and it isn't the interesting part:

evalLetrec env [SList [SList [SSymbol f, SList [SSymbol "lambda", SList params, fbody]]], body] =

The pattern names the parts:

  • f: the name being bound
  • params: the lambda's parameters
  • fbody: the lambda's body
  • body: the letrec's own body

(symbolName, in RaskAST.hs, gets the name out of an SSymbol. VClosure, in the same file, is how a closure value is built.)

Writing it yourself, or using the solution:

  • Figure it out yourself. The whole puzzle is one question: which environment should the closure for f remember? It has to be one in which f is bound to... that very closure. If you get stuck, here are two hints, in order:
    1. Haskell is lazy. A definition can mention something that isn't finished yet, as long as nobody looks inside it too early.
    2. The library loader, define in Rask.hs, does something closely related for library files.
  • Use the solution. Copy it from How letrec Works. That page also explains, step by step, why it works.

If you copy the solution, read the explanation, because the "Think about it" questions below ask about it.

Think about it

  1. Why does the let version of down fail, while the letrec version works? Answer in terms of which environment each closure remembers.
  2. The solution's evalLetrec has two definitions that refer to each other (see How letrec Works). Suppose you translated it line for line into a strict language like Python, where every definition is evaluated immediately. What would go wrong at those two definitions? (Real interpreters for strict languages usually create the environment first, then mutate it to add the closure.)

Optional: the Y combinator

This one is optional. In Module 08.3, you got recursion with no named functions at all, using the Y combinator. Try it in Raskell: define Y with a let, and use it to define factorial. What happens, and why? (Raskell uses call by value. If you get stuck, look up the Z combinator.)

✅ Check your work (Stage 3)

./run-tests 03 should pass all 13 tests. The two letrec tests need Stages 1 and 2 as well, and a working evalLetrec.


Stage 4: Lists and Higher-Order Functions

Try these in rask-reference first

Before you write any code, start rask-reference and type in each expression in the table below. Predict the result before you press Enter. If anything surprises you, especially the last row, work out why before going on. You'll use the same expressions to check your own code at the end of this stage.

Expression Result
(list 'a (+ 1 2) 'c) (a 3 c)
(append '(a b) '(c d)) (a b c d)
(map (lambda (x) (* x 2)) '(1 2 3)) (2 4 6)
(map first '((a b) (c d))) (a c)
(foldl (lambda (x acc) (+ x acc)) 0 '(1 2 3)) 6
(foldl cons '() '(a b c)) (c b a)

list takes any number of arguments. append takes exactly two lists.

Implement: primList, primAppend, primMap, primFoldl

In RaskEval.hs, replace each placeholder marked TODO (Stage 4). All four are primitives, like the ones in Stage 1:

Function Implements
primList list
primAppend append
primMap map
primFoldl foldl

primMap and primFoldl call their function argument with apply, as explained below.

The interesting ones are map and foldl. Their first argument is a Raskell function. It might be either of these:

  • a primitive, like first
  • a closure, like (lambda (x) (* x 2)), which has a body that only the evaluator knows how to run

Your Haskell code can't call it directly. Use apply, the same function the evaluator uses for every function call, and it handles both kinds.

foldl's argument order is Racket's, not Haskell's

Raskell follows Racket: (foldl f init xs) calls f with the element first and the accumulator second.

(foldl f init '(a b c))   =   (f c (f b (f a init)))

Haskell's foldl passes them the other way around. So (foldl cons '() '(a b c)) is (c b a), and (foldl (lambda (x acc) (- x acc)) 0 '(1 2 3)) is 2. Check that one by hand.

✅ Check your work (Stage 4)

./run-tests 04 should pass all 18 tests.

Then try your list functions by hand. Start the REPL with ./rask, type each expression, and check that you get the result in the comment. These are the expressions from the top of this stage, plus a few more. If any result differs, run the same expression in rask-reference.

list and append:

(list 'a (+ 1 2) 'c)          ; (a 3 c)
(list)                        ; ()
(append '(a b) '(c d))        ; (a b c d)
(append '() '(c d))           ; (c d)

map, with a closure and with a primitive:

(map (lambda (x) (* x 2)) '(1 2 3))   ; (2 4 6)
(map first '((a b) (c d)))            ; (a c)

A closure that uses a variable from outside it. apply has to run the closure's body in the environment the closure remembers, where k is 10:

(let ((k 10)) (map (lambda (x) (+ x k)) '(1 2 3)))   ; (11 12 13)

foldl, element first and accumulator second:

(foldl (lambda (x acc) (+ x acc)) 0 '(1 2 3))   ; 6
(foldl cons '() '(a b c))                       ; (c b a)
(foldl (lambda (x acc) (- x acc)) 0 '(1 2 3))   ; 2

Errors. Each of these should print some error: message:

(append '(a) 'b)                ; the second argument isn't a list
(map + '(1 2))                  ; + gets one argument, not two
(map (lambda (x y) x) '(1 2))   ; the lambda needs two arguments

Stage 5: A Library Written in Raskell

Raskell doesn't have reverse or filter. You could add them to RaskEval.hs as more primitives, but you won't. Instead, you write them in Raskell, using the features you just built.

Expression Result
(reverse '(a b c)) (c b a)
(reverse '()) ()
(filter (lambda (x) (< x 4)) '(1 5 3 7 2)) (1 3 2)

filter keeps the elements in their original order.

Implement, in Raskell: reverse and filter

In rasklib/list-library.rask, replace each 'TODO with a real body. Write them in Raskell, using the features from Stages 1 to 4. Don't add them to RaskEval.hs.

Raskell has no global define, so a library is a file holding one list of definitions:

( (reverse (lambda (xs) ...))
  (filter  (lambda (keep? xs) ...)) )

--lib loads a library in front of a program. The starter includes a program that uses reverse and filter, programs/library-demo.rask:

((lambda (nums)
   (list (reverse nums)                                  ; backward
         (filter (lambda (x) (< x 4)) nums)              ; the small ones
         (reverse (filter (lambda (x) (= 0 (modulo x 2)))
                          nums))))                       ; the evens, backward
 '(1 5 3 7 2 4))

Run it with your library loaded in front of it:

./rask --lib rasklib/list-library.rask --file programs/library-demo.rask

Once your library works, it prints ((4 2 7 3 5 1) (1 3 2) (4 2)). Without --lib, reverse and filter aren't defined, so you get error: unbound identifier: reverse. To check your library separately from your Haskell, run the same command with rask-reference in place of ./rask. That runs your library on the reference interpreter.

For quicker experiments, start a REPL with the library loaded:

./rask --lib rasklib/list-library.rask

The definitions load in order, so a later one can use an earlier one. A definition whose value is a lambda can also call itself, as if it were bound by letrec.

You can write them either of two ways:

  • With recursion, the way you'd write them in Haskell. Use empty? for the base case, and first and rest to take the list apart. A definition can call itself by name.
  • With foldl, which visits every element in order, while you decide what to build. One of the examples in Stage 4 is most of reverse already.

Try both, if you have time. They make a good comparison.

✅ Check your work (Stage 5)

./run-tests 05 should pass all 11 tests. Two of them check that reverse and filter are not in RaskEval.hs. To test your Raskell code alone, try ./run-tests --reference 05.

Then run the demo program, and check that it prints ((4 2 7 3 5 1) (1 3 2) (4 2)):

./rask --lib rasklib/list-library.rask --file programs/library-demo.rask

Then start a REPL with your library loaded, using ./rask --lib rasklib/list-library.rask, and try these. Check that you get the result in the comment.

reverse:

(reverse '(a b c))           ; (c b a)
(reverse '())                ; ()
(reverse '((a b) c))         ; (c (a b))   only the outer list is reversed

filter, which keeps the elements in their original order:

(filter (lambda (x) (< x 4)) '(1 5 3 7 2))              ; (1 3 2)
(filter (lambda (x) (> x 100)) '(1 2 3))                ; ()
(filter (lambda (s) (= 0 (modulo s 2))) '(1 2 3 4 5 6)) ; (2 4 6)
(filter empty? '((a) () (b c) ()))                      ; (() ())

The two together:

(reverse (filter (lambda (x) (< x 4)) '(1 5 3 7 2)))    ; (2 3 1)

If a result surprises you, run the same thing with rask-reference --lib rasklib/list-library.rask. If you get the same surprise, the bug is in your Raskell library. If you don't, the bug is in your Haskell from Stages 1 to 4.

Think about it

You've now added features to Raskell in two different ways. You wrote map in Haskell, and filter in Raskell. What's different about where each one lives, and about who could add a function like filter (a Raskell programmer, or only the person maintaining the interpreter)? Could if have been written in Raskell the way filter was?


Stage 6: Collatz in Your Own Language

Here's the Collatz rule, one last time. Starting from a positive integer n:

  • if n is even, the next number is n / 2;
  • if n is odd, the next number is 3n + 1.

Repeat until you reach 1. (Nobody has proved that every starting number gets there. Every number anyone has tried does, including all the ones we test.)

programs/collatz.rask is a single S-expression whose value is a function of n. That function returns a list of four things about the sequence starting at n:

(sequence  length  even-elements  reversed-sequence)
  • sequence: the Collatz sequence from n down to 1
  • length: how many numbers are in the sequence
  • even-elements: the even numbers in the sequence, in order
  • reversed-sequence: the sequence backward, from 1 up to n

For n = 6:

((6 3 10 5 16 8 4 2 1) 9 (6 10 16 8 4 2) (1 2 4 8 16 5 10 3 6))

When the program's value is a function, the file runner applies it to each number you give on the command line:

./rask --lib rasklib/list-library.rask --file programs/collatz.rask 6 7

Implement, in Raskell: programs/collatz.rask

The starter file gives you the program's shape, with 'TODO-... symbols to replace. Keep the overall shape, and replace the symbols by working through Milestones A to C below, in order.

Milestone A: one step. Write next, which takes n to the next number in the sequence. Use modulo to decide whether n is even and quotient to halve it. Test it on its own in the REPL before moving on.

Milestone B: the whole sequence. Write collatz, using letrec, so that (collatz n) is the list of numbers from n down to and including 1:

(collatz 6)   ; (6 3 10 5 16 8 4 2 1)
(collatz 7)   ; (7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1)
(collatz 1)   ; (1)

Milestone C: analyze it with your library. Fill in the other three fields of the result:

  • Use foldl for the length.
  • Use filter for the even elements.
  • Use reverse for the reversed sequence.

All three use the functions from Stages 4 and 5. Don't write new recursion for them.

Milestone D: run it. Run the file on several inputs, then run the tests.

✅ Check your work (Stage 6)

./run-tests 06 runs your program on 1, 2, 6, 7, and 27. To check your Raskell program alone, use ./run-tests --reference 06. If it passes with the reference interpreter but fails with yours, the bug is in your Haskell.

Think about it

Now that you've written a real program in Raskell, what's one feature of the language that made it easier, and one thing that was awkward or missing? Point to a specific spot in your collatz.rask.


Turning It In

Submit on Gradescope, under HW 09: Raskell:

  1. From the top of the repo, run the tests one last time: ./run-tests > testing.log. Paste the entire contents of testing.log into the test-output text box, even if some tests still fail.
  2. Upload the three files you edit:
    • RaskEval.hs
    • rasklib/list-library.rask
    • programs/collatz.rask

Gradescope also asks a few short questions, several of them from the "Think about it" boxes on this page.

The Homework Workflow covers the submission step in context. Make sure your final code is committed and pushed to your repo as well.

Final Self-Check

  • ./run-tests compiles and runs, and shows the total you expect.
  • No notImplemented placeholders are left in RaskEval.hs.
  • reverse and filter are written in rasklib/list-library.rask, not in RaskEval.hs.
  • programs/collatz.rask is one S-expression, and uses:
    • letrec
    • foldl
    • filter
    • reverse
  • You didn't change the provided files (including ParserCombinators.hs, ParserBase.hs, and tests/).

Where to Go From Here

Look at how Collatz has followed you through the course:

Assignment How you wrote Collatz
HW 2 In Haskell, a language someone else built.
HW 8 In the lambda calculus, with nothing but functions.
HW 9 In Raskell, a language you built, running on an interpreter you wrote.

The new part isn't computing another Collatz sequence. It's that the ideas from the whole course fit together into a working programming language:

  • parsing
  • code as data
  • environments
  • closures
  • special forms
  • functions as values

If you'd like to go further, chapter 4 of Structure and Interpretation of Computer Programs, Metalinguistic Abstraction, builds a Lisp interpreter written in Lisp itself. That's the same idea as Raskell, with the host and guest languages being one and the same.


Optional Challenge: The Roots of Lisp

In 1960, John McCarthy built a whole programming language from seven primitive operators, then wrote that language's eval in the language itself. Paul Graham's essay The Roots of Lisp walks through how he did it. If you'd like a very ambitious, ungraded project after you submit, you can rebuild McCarthy's evaluator yourself, either in Racket or in Raskell, the language you just built.

Take the challenge →