rackettyped-racket

Sum types in Racket/TypedRacket


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

For example: data MusicGenre = HeavyMetal | Pop | HardRock


Solution

  • 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"