DNA 가닥의 각 염기가 각각 몇 개 있는지 세는 문제였다. 이럴 때 쓰라고 만든 듯한 아주 좋은 함수 Enum.frequencies/1
이 있어서 편하게 구현할 수 있었다. histogram
함수에서 반환되는 맵에 키가 고정되어 있어야 해서 구조체를 쓸까 하고도 생각했는데, 굳이 구조체를 정의하지 않아도 주어진 키로 맵 기본값을 만들어 두고 맵을 병합하는 것으로 충분할 것 같아 그렇게 작성했다.
defmodule NucleotideCount do
@nucleotides [?A, ?C, ?G, ?T]
@spec count(charlist(), char()) :: non_neg_integer()
def count(strand, nucleotide) do
strand |> histogram() |> Map.get(nucleotide, 0)
end
@spec histogram(charlist()) :: map()
def histogram(strand) do
Map.new(@nucleotides, fn v -> {v, 0} end)
|> Map.merge(Enum.frequencies(strand))
end
end
'호두나무 공방 > Exercism in Elixir' 카테고리의 다른 글
Pangram - Exercism in Elixir (0) | 2022.05.31 |
---|---|
Triangle - Exercism in Elixir (0) | 2022.05.30 |
Remote Control Car - Exercism in Elixir (0) | 2022.05.12 |
Chessboard - Exercism in Elixir (0) | 2022.05.11 |
Hamming - Exercism in Elixir (0) | 2022.05.10 |