简体   繁体   中英

Sum types in Racket/TypedRacket

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

For example: data MusicGenre = HeavyMetal | Pop | HardRock data MusicGenre = HeavyMetal | Pop | HardRock

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM