RacketTyped-RacketStatic-TypingGradual-Typing
Typed Racket: From Dynamic to Static | Schema Programming Part 13
2.71 min read
Md Nasim Sheikh
Racket is dynamic by default. But as projects grow, types become useful for documentation and safety. Typed Racket is a sister language that adds a static type system.
Advertisement
The Language
Change #lang racket to #lang typed/racket.
#lang typed/racket
(: add (-> Number Number Number))
(define (add x y)
(+ x y))
(add 5 10) ; Works
; (add "hello" 5) ; Compile-time Type Error!
Type Annotations
Use the (: id type) syntax (the "colon" form) to annotate definitions.
NumberStringBoolean(Listof Number)Any
Gradual Typing
The killer feature of Typed Racket is interop. You can have untyped code call typed code and vice-versa. Contracts are automatically generated at the boundary to ensure safety!
Polymorphism
(: my-map (All (A B) (-> (-> A B) (Listof A) (Listof B))))
(define (my-map f L)
(if (null? L)
'()
(cons (f (first L)) (my-map f (rest L)))))
Advertisement
Summary
Typed Racket allows you to start fast (dynamic) and harden later (static) without rewriting your entire codebase in a different language.
Quick Quiz
What is the specialized `#lang` for the statically typed version of Racket?
Written by
Md Nasim Sheikh
Software Developer at softexForge
Verified Author150+ Projects
Published: