Reputation: 403
What would be the Racket/TypedRacket equivalent of Haskell's sum types?
For example:
data MusicGenre = HeavyMetal | Pop | HardRock
Upvotes: 1
Views: 157
Reputation: 421
You may also be interested in define-datatype
provided by typed-racket-datatype. You can combine that with match
from racket/match to branch on the cases.
Upvotes: 0
Reputation: 52334
You can use define-type
and a union of symbols for this kind of sum type:
$ racket -I typed/racket
Welcome to Racket v8.7 [cs].
> (define-type MusicGenre (U 'HeavyMetal 'Pop 'HardRock))
> (define x (ann 'Pop MusicGenre))
> (define y (ann 'Jazz MusicGenre))
string:1:15: Type Checker: type mismatch
expected: MusicGenre
given: 'Jazz
in: (quote Jazz)
[,bt for context]
> (define (best-genre [g : MusicGenre]) (if (eq? g 'HardRock) "You know it" "Loser"))
> best-genre
- : (-> MusicGenre String)
#<procedure:best-genre>
> (best-genre 'Jazz)
string:1:12: Type Checker: type mismatch
expected: MusicGenre
given: 'Jazz
in: (quote Jazz)
[,bt for context]
> (best-genre 'HardRock)
- : String
"You know it"
Upvotes: 1