컴프리헨션은 _Enumerable_을 쉽고 선언적으로 변환하는 기능을 제공해요.
아주 간단한 컴프리헨션을 선언하려면, for 키워드 뒤에 _제너레이터_와 열거된 값에서 새로운 값을 만드는 _do 블록_을 사용하면 돼요.
for n <- [0, 1, 2, 3], do: n + 1
# => [1, 2, 3, 4]
컴프리헨션에는 _필터_를 둘 수도 있어요. 필터를 통과하지 못한 값은 최종 배열에서 제거돼요:
for n <- [0, 1, 2, 3], n > 1, do: n + 1
# => [3, 4]
여러 줄에 걸쳐 더 복잡한 컴프리헨션을 선언할 수 있어요:
for {atom, number} <- [a: 1, b: 2, c: 3, d: 4],
rem(number, 2) == 0 do
atom
end
# => [:b, :d]
_카테시안 곱_은 여러 제너레이터를 사용해 만들 수 있어요. 즉, 첫 번째 제너레이터가 생성한 각 값은 두 번째 제너레이터가 생성한 각 값과 한 번씩 짝을 이뤄요:
for x <- [0, 1],
y <- [0, 1] do
{x, y}
end
# => [{0, 0}, {0, 1}, {1, 0}, {1, 1}]
온라인 패션 부티크 매장에서의 일은 계속돼요. 사용자에게 코디를 추천해 주는 웹사이트 기능을 떠올려요. 제안을 많이 해 주고 싶지만, 좋지 않은 제안을 하고 싶지는 않아요. 그래서 리스트 컴프리헨션을 사용하기로 해요. 코디 조합을 쉽게 _생성_한 다음, 몇 가지 기준으로 _필터링_할 수 있거든요.
의류 품목은 맵으로 저장돼요:
%{
item_name: "Descriptive Name",
price: 99.00,
color: "Ochre Red",
base_color: "red"
}
get_combinations/3 함수를 구현해요. 이 함수는 상의 목록, 하의 목록, 그리고 옵션 키워드 목록을 받아요. 지금은 옵션의 기본값을 빈 키워드 목록으로 설정해요. 이 함수는 두 목록의 카테시안 곱을 반환해야 해요.
tops = [
%{item_name: "Dress shirt"},
%{item_name: "Casual shirt"}
]
bottoms = [
%{item_name: "Jeans"},
%{item_name: "Dress trousers"}
]
BoutiqueSuggestions.get_combinations(tops, bottoms)
# => [
# {%{item_name: "Dress shirt"}, %{item_name: "Jeans"}},
# {%{item_name: "Dress shirt"}, %{item_name: "Dress trousers"}},
# {%{item_name: "Casual shirt"}, %{item_name: "Jeans"}},
# {%{item_name: "Casual shirt"}, %{item_name: "Dress trousers"}}
# ]
옷마다 :base_color 필드가 있어요. 이 필드를 사용해서 상의와 하의의 기본 색상이 같은 조합은 모두 걸러내요.
tops = [
%{item_name: "Dress shirt", base_color: "blue"},
%{item_name: "Casual shirt", base_color: "black"}
]
bottoms = [
%{item_name: "Jeans", base_color: "blue"},
%{item_name: "Dress trousers", base_color: "black"}
]
BoutiqueSuggestions.get_combinations(tops, bottoms)
# => [
# {%{item_name: "Dress shirt", base_color: "blue"},
# %{item_name: "Dress trousers", base_color: "black"}},
# {%{item_name: "Casual shirt", base_color: "black"},
# %{item_name: "Jeans", base_color: "blue"}}
# ]
옷마다 :price 필드가 있어요. 제안을 많이 해 주고 싶지만, 사용자가 예산 안에서 가격을 선택할 수 있는 기회도 주고 싶어요. 옵션 키워드 목록에서 :maximum_price를 사용해, 상의와 하의의 가격이 최대 가격을 넘는 조합을 걸러내요.
maximum_price를 지정하지 않으면 기본값은 100.00이어야 해요.
tops = [
%{item_name: "Dress shirt", base_color: "blue", price: 35},
%{item_name: "Casual shirt", base_color: "black", price: 20}
]
bottoms = [
%{item_name: "Jeans", base_color: "blue", price: 30},
%{item_name: "Dress trousers", base_color: "black", price: 75}
]
BoutiqueSuggestions.get_combinations(tops, bottoms, maximum_price: 50)
# => [
# {%{item_name: "Casual shirt", base_color: "black", price: 20},
# %{item_name: "Jeans", base_color: "blue", price: 30}}
# ]
Exercism에 가입하고 Elixir 트랙을 개념 58개연습 문제 168개, 그리고 실제 사람의 멘토링과 함께 배우고 익혀 보세요. 모두 무료예요.