2016-04-29 21 views
0

アイテムのリストが与えられている場合、どのように特定の構造体をフィルタリングできますか?ELIXIR:特定の構造体のリストをフィルタリングする方法

例:

は、私たちは、あなたがこのためにforを使用することができる唯一の%TL.DocumentAttributeFilename{}

lst1 = [%TL.DocumentAttributeImageSize{h: 1280, w: 960}, %TL.DocumentAttributeFilename{file_name: "422305695_81769.jpg"}] 
lst2 = [%TL.DocumentAttributeVideo{duration: 7, h: 224, w: 264}, %TL.DocumentAttributeFilename{file_name: "animation.gif.mp4"}, %TL.DocumentAttributeAnimated{}] 

答えて

6

リスト内の項目から必要:考える

defmodule A do 
    defstruct [letter: :a] 
end 

defmodule B do 
    defstruct [letter: :b] 
end 

あなたが行うことができます:

iex(1)> list = [%A{}, %B{}, %A{}, %A{}, %B{}] 
[%A{letter: :a}, %B{letter: :b}, %A{letter: :a}, %A{letter: :a}, %B{letter: :b}] 
iex(2)> for %A{} = a <- list, do: a 
[%A{letter: :a}, %A{letter: :a}, %A{letter: :a}] 

forは、指定されたパターンと一致しないすべての項目を無視するため、これが機能します。

あなたはまた起きる何の操作、それは明確にするために Enum.filterを使用することができます
+0

、感謝 –

0

Enum.filter(lst1, fn(x) -> %TL.DocumentAttributeFilename{} == x end) 

Dogbertは、上記の式は、デフォルトのフィールド値を持つTL.DocumentAttributeFilename構造体ですlst1の要素のみを維持する観察されたように - ない何を求めました。華麗

Enum.filter(lst1, fn(x) -> x.__struct__ == TL.DocumentAttributeFilename end) 
+2

'X'は、構造体 'TL.DocumentAttributeFilename'のすべてのフィールドにデフォルト値を持っている場合にのみ一致します。

はここlst1のすべてTL.DocumentAttributeFilename構造体を維持するバージョンです。 – Dogbert

関連する問題