연상을 사용한 패턴 매칭
버전 11에서는 연상 작업의 패턴 매칭과 조작을 간단하게하는 여러 함수를 도입하였습니다.
KeyMemberQ와 KeyFreeQ를 사용하여 키가 연상의 일부인지 여부를 테스트합니다.
In[1]:=
![Click for copyable input](assets.ko/pattern-matching-with-associations/In_72.png)
KeyMemberQ[<|a -> 1, b -> 2, c -> 3|>, a]
Out[1]=
![](assets.ko/pattern-matching-with-associations/O_75.png)
In[2]:=
![Click for copyable input](assets.ko/pattern-matching-with-associations/In_73.png)
KeyFreeQ[<|a -> 1, b -> 2, c -> 3|>, a]
Out[2]=
![](assets.ko/pattern-matching-with-associations/O_76.png)
KeyValuePattern을 사용하면 지정된 규칙을 하나 이상 포함하는 연상 전체를 매치 할 수있습니다.
In[3]:=
![Click for copyable input](assets.ko/pattern-matching-with-associations/In_74.png)
MatchQ[<|a -> 1, b -> 2, c -> 3|>, KeyValuePattern[b -> _]]
Out[3]=
![](assets.ko/pattern-matching-with-associations/O_77.png)
In[4]:=
![Click for copyable input](assets.ko/pattern-matching-with-associations/In_75.png)
MatchQ[<|a -> 1, b -> 2, c -> 3|>, KeyValuePattern[{c -> _, a -> _}]]
Out[4]=
![](assets.ko/pattern-matching-with-associations/O_78.png)
지구상의 여러 지점에서 중력장에 대한 데이터를 계산합니다.
In[5]:=
![Click for copyable input](assets.ko/pattern-matching-with-associations/In_76.png)
points = {{40, -100, 691}, {30, -120, 560}, {80, 70, 91}};
data = GeogravityModelData /@ points
Out[5]=
![](assets.ko/pattern-matching-with-associations/O_79.png)
필드 규모가 평균값 보다 큰 몇 곳을 선택합니다.
In[6]:=
![Click for copyable input](assets.ko/pattern-matching-with-associations/In_77.png)
Cases[data,
KeyValuePattern[
"Magnitude" -> _?(GreaterThan[
Quantity[1, "StandardAccelerationOfGravity"]])]]
Out[6]=
![](assets.ko/pattern-matching-with-associations/O_80.png)
KeyValueMap을 사용하여 키와 값 쌍을 추가로 처리합니다.
In[7]:=
![Click for copyable input](assets.ko/pattern-matching-with-associations/In_78.png)
Cases[data,
KeyValuePattern[
"Magnitude" -> _?(GreaterThan[
Quantity[1, "StandardAccelerationOfGravity"]])]];
KeyValueMap[
EntityProperty["GeogravityModel", #1] ->
UnitConvert[#2, "Imperial"] &, First[%]]
Out[7]=
![](assets.ko/pattern-matching-with-associations/O_81.png)