Sum types in Racket/TypedRacket

106 Views Asked by At

What would be the Racket/TypedRacket equivalent of Haskell's sum types?

For example: data MusicGenre = HeavyMetal | Pop | HardRock

2

There are 2 best solutions below

0
Shawn On BEST ANSWER

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"
0
Srikumar On

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.