Difference between revisions of "Ko/PatternSynonyms"

From HaskellWiki
Jump to navigation Jump to search
(문서 생성)
 
m (설명 및 참고 분류 추가)
Line 36: Line 36:
 
arrows = flip $ foldr Arrow
 
arrows = flip $ foldr Arrow
 
</haskell>
 
</haskell>
  +
  +
아래 코드는 <hask><-</hask>로 패턴 별명을 정의하는 건 가능하지만 <hask>=</hask>로 정의하는 것은 안 된다.
  +
  +
<haskell>
  +
pattern ThirdElem x = _:_:x:_
  +
pattern Snd y = (x, y)
  +
</haskell>
  +
  +
== 참고 ==
  +
  +
* [https://gitlab.haskell.org/ghc/ghc/-/wikis/pattern-synonyms 하스켈 깃랩 위키]
  +
* [https://hackage.haskell.org/package/time-1.12.2/docs/src/Data.Time.Calendar.Gregorian.html#YearMonthDay 패턴 별명을 사용한 사례]
   
 
[[Category:Korean]]
 
[[Category:Korean]]

Revision as of 12:10, 22 November 2023

PatternSynonyms는 GHC 확장이다.

아래와 같은 타입이 있을 때

data Type = App String [Type]

다음과 같이 패턴 매칭할 수 있다.

collectArgs :: Type -> [Type]
collectArgs (App "->" [t1, t2]) = t1 : collectArgs t2
collectArgs _ = []

이때 아래와 같이 패턴에 Arrow라는 이름을 지어주면

pattern Arrow t1 t2 <- App "->" [t1, t2]

다음과 같이 이름 Arrow를 이용해서 패턴 매칭할 수 있다.

collectArgs :: Type -> [Type]
collectArgs (Arrow t1 t2) = t1 : collectArgs t2

패턴 별명(Pattern Synonyms)을 지을 때 키워드 pattern<-를 사용했는데 <- 대신 =를 쓰면 다음과 같이 패턴 매칭 뿐만 아니라 표현식에서도 이름 Arrow를 사용할 수 있다.

pattern Arrow t1 t2 = App "->" [t1, t2]

arrows :: [Type] -> Type -> Type
arrows = flip $ foldr Arrow

아래 코드는 <-로 패턴 별명을 정의하는 건 가능하지만 =로 정의하는 것은 안 된다.

pattern ThirdElem x = _:_:x:_
pattern Snd y = (x, y)

참고