[racket] user's guide feedback/questions as I prepare for my PL course
> b. "you can show them an untyped/typed interaction that is
> eye-opening for the better students and shows them something truly on
> the cutting edge of PL research" -- now this is very intriguing and
> sounds like a great addition to the lecture on static/dynamic typing.
> Hopefully Shriram (to call him out by name) will reply to the list
> with a fleshed out description of the example he uses
There are several different ways of setting up even this illustration.
Here is one of them. There are three "files" below.
===== untyped-sort.rkt =====
#lang racket
(define (isort l)
(cond
[(empty? l) l]
[(cons? l) (insert (first l)
(isort (rest l)))]))
(provide isort)
(define (insert e l)
(cond
[(empty? l) (cons e l)]
[(cons? l) (if (<= e (first l))
(cons e l)
(cons (first l)
(insert e (rest l))))]))
==========
===== typed-sort.rkt =====
#lang typed/racket
(: isort ((Listof Real) -> (Listof Real)))
(define (isort l)
(cond
[(empty? l) l]
[(cons? l) (insert (first l)
(isort (rest l)))]))
(provide isort)
(: insert (Real (Listof Real) -> (Listof Real)))
(define (insert e l)
(cond
[(empty? l) (cons e l)]
[(cons? l) (if (<= e (first l))
(cons e l)
(cons (first l)
(insert e (rest l))))]))
==========
===== client.rkt (or an unsaved buffer will do) =====
#lang racket
(require [prefix-in ut: "untyped-sort.rkt"])
(require [prefix-in ty: "typed-sort.rkt"])
;; These two will work
(and (equal? (ut:isort (list 3 1 2)) (list 1 2 3))
(equal? (ty:isort (list 3 1 2)) (list 1 2 3)))
;; This won't work:
;(ut:isort (list "abc" "xyz"))
;;with this error message:
; untyped-sort.rkt:14:19: <=: expects type <real number> as 1st
argument, given: "abc"; other arguments were: "xyz"
;; This won't work either:
;(ty:isort (list "abc" "xyz"))
;; with this (VERY DIFFERENT) error message:
;isort2: contract violation, expected <Real>, given: "abc"
; contract from
; C:\Users\sk\Desktop\typed-sort.rkt
; blaming anonymous-module
; contract:
; (-> (listof Real) (listof Real))
==========
There are many variations on this, eg, where the untyped code imports
the implementation from the typed code, typed from untyped, contracts
on the untyped.
Hopefully you'll also have a skeptical student who wonders where the
violation was actually caught in the typed version -- put differently,
how much of the typed code ran? Modify it:
(define (isort l)
(printf "got here~n")
(cond ...
You see several lines of output in "good calls", but none for the bad
one, showing that the typed function *never even ran*.
Shriram