새소식

Programming/Elm

[Elm] 유니온 타입 (Union Type)

  • -

Union Type은 타 언어의 Enum Class와 비슷하다.

Elm 에서 Union Type을 Tag 라고도 부른다.

 

선언 방법

type Answer
    = Yes
    | No

활용 예시

respond : Answer -> String
respond answer =
    case answer of
        Yes ->
            "Good"

        No ->
            "Bad"
> respond Yes
"Good" : String

> respond No
"Bad" : String

 

포함 하기

Union Type은 관련된 정보를 포함할 수 있다.

type Answer
    = Yes
    | No
    | Other String

Other 태그는 String을 포함한다. 정의되었던 respond 함수를 다음과 같이 호출할 수 있다.

respond : Answer -> String
respond answer =
    case answer of
        Yes ->
            "Good"

        No ->
            "Bad"

        Other str ->
            str
> respond (Other "I don't know")
"I don't know" : String

 

중첩 하기

Union Type이 다른 Unio Type에 중첩되는 경우 아래와 같이 활용할 수 있다.

type OtherAnswer
    = DontKnow
    | Perhaps
    | Undecided


type Answer
    = Yes
    | No
    | Other OtherAnswer
respondOther : OtherAnswer -> String
respondOther otherAnswer =
        case otherAnswer of
            DontKnow ->
                "I don't Know"

            Perhaps ->
                "I do it sometimes."

            Undecided ->
                "It is undecided"



respond : Answer -> String
respond answer =
    case answer of
        Yes ->
            "Good"

        No ->
            "Bad"

        Other otherAnswer ->
            respondOther otherAnswer
> respond (Other DontKnow)
"I don't Know" : String

> respond (Other Perhaps)
"I do it sometimes." : String

> respond (Other Undecided)
"It is undecided" : String

 

타입 변수

타입 변수도 사용할 수 있다.

type Answer a
    = Yes
    | No
    | Other a
respond : Answer Int -> String
respond answer =
    case answer of
        Yes ->
            "Good"

        No ->
            "Bad"

        Other a ->
            "IntPut Num: " ++ String.fromInt a
> respond (Other 123456789)
"IntPut Num: 123456789" : String

'Programming > Elm' 카테고리의 다른 글

[Elm] 함수 파이프 연산자 (Pipe Operator)  (0) 2020.11.24
[Elm] 함수 (Function)  (0) 2020.11.24
[Elm] 변수 (Variable)  (0) 2020.11.20
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.