LoginSignup
5
0

More than 3 years have passed since last update.

[Elm] typeとtype aliasの違い

Posted at

背景

ずっとReactやReact Nativeを使って開発をしていたのですが、最近になってElmを触り始めました。
むむっとなったelm記法のtypeとtype aliasの違いを書いていきます。

type alias

まずはtype aliasについて書いていきます。
type aliasは型の別名をつけることができます。

hasName : { id : Int, name : String } -> Bool
hasName user = 
    String.length user.name > 0

上記のような関数がある時、{ id : Int, name : String }の部分が冗長ですし、何を表しているのかわかりません。
そこでtype aliasを使って型に別名をつけてあげます。

type alias User =
    { id: Int
    , name: String
    }

hasName : User -> Bool
hasName user =
   String.length user.name > 0

type aliasを使ってわかりやすくなりました。
こういったように自分の表現したい型に対して別名をつけることがtype aliasです。

type

typeはtype aliasとは別の物です。
typeはカスタム型と呼ばれ、新たな型を自分で定義できます。

type Country = Japan | Korea | China | Thailand | Taiwan

上記の例はCountry型という新たな型を作りました。
注意するべきなのが、Countryはですが、Japanはということです。
Boolという型は以下のように定義されています。

type Bool = True | False

このように考えるとイメージしやすいです。
またカスタム型は列挙するだけでなく、それぞれに値を保持することもできます。

type User
    = Member String
    | Guest

user1 : User
user1 = Member "akira"

user2 : User
user2 = Guest

message : User -> String
message user =
    case user of
        Member name ->
            "こんにちは, " ++ name ++ "さん"
        Guest ->
            "こんにちは"

上記のような関数が作れます。

まとめ

type aliasとtypeの違いを書いてみました。
同じような意味合いだと最初は思っていたのですが、全然違いました。
参考になれば幸いです。

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0