nikita-volkov / typeclasses

Explicit typeclasses for Elm
https://package.elm-lang.org/packages/nikita-volkov/typeclasses/latest/
MIT License
54 stars 3 forks source link

Extend documentation with recipies of constructing instances of Hashing for composite types (sums, products, enums) #4

Open nikita-volkov opened 5 years ago

nikita-volkov commented 5 years ago

It's not obvious currently how the API can be used to achieve that.

This thread is intended for collection of examples, which you're very welcome to post as comments.

nikita-volkov commented 5 years ago

As a starter, here's two alternative recipies for an instance of a sum-type:

type FontLocation =
  GoogleFontLocation | UriFontLocation String | LocalFontLocation

fontLocationThruEither : Hashing FontLocation
fontLocationThruEither =
  either int (string 3) |>
  map (\ a -> case a of
    GoogleFontLocation -> Either.Left 0
    UriFontLocation b -> Either.Right b
    LocalFontLocation -> Either.Left 1)

fontLocationThruProduct : Hashing FontLocation
fontLocationThruProduct =
  concat
    [
      map .tag int,
      map .uri (string 3)
    ] |>
  map (\ a -> case a of
    GoogleFontLocation -> {tag = 0, uri = ""}
    UriFontLocation b -> {tag = 1, uri = b}
    LocalFontLocation -> {tag = 2, uri = ""})
nikita-volkov commented 5 years ago

Here's an example of an enum:


type FontWeight =
  ThinFontWeight |
  UltraLightFontWeight |
  LightFontWeight |
  NormalFontWeight |
  MediumFontWeight |
  SemiBoldFontWeight |
  BoldFontWeight |
  UltraBoldFontWeight |
  BlackFontWeight |
  UltraBlackFontWeight

fontWeight : Hashing FontWeight
fontWeight =
  int |>
  map (\ a -> case a of
    ThinFontWeight -> 0
    UltraLightFontWeight -> 1
    LightFontWeight -> 2
    NormalFontWeight -> 3
    MediumFontWeight -> 4
    SemiBoldFontWeight -> 5
    BoldFontWeight -> 6
    UltraBoldFontWeight -> 7
    BlackFontWeight -> 8
    UltraBlackFontWeight -> 9)