Elixir入門「番外編:Elixir+Phoenixで弱々しいAIを作る、の裏側」
- 6. 5
#4の裏話や解説など
このスライドは、ほぼ#4のコード解説のために作ったようなもんです(^^)
まず、lib/cabocha.exの下記ですが、何しているコードか分かりますか?
これは、 「Regex.named_captures()」 を使って、「文字列が正規表
現でパターンマッチしたら、それをマップに変換」しているのです
def feature_map( feature ) do
Regex.named_captures( ~r/
^
(?<part_of_speech>[^,]*),
*?(?<part_of_speech_subcategory1>[^,]*),
*?(?<part_of_speech_subcategory2>[^,]*),
*?(?<part_of_speech_subcategory3>[^,]*),
*?(?<conjugation_form>[^,]*),
*?(?<conjugation>[^,]*),
(?<lexical_form>[^,]*),
(?<yomi>[^,]*),
(?<pronunciation>.*)
$
/x, feature )
end
- 8. 7
defmodule Relation do
…
def nodes( terminate_id, [ %{ "chunk" => %{ "id" => id, "link" => link } } | tail ], body, node_ids ) do
concat_node_ids = case terminate_id == [ link ] do
true ->
inner_ids = case link == "-1" do
true -> []
false ->
[ ids ] = Enum.map( [ id ], &( nodes( [ &1 ], body, body, [] ) ) )
ids
end
case inner_ids == [] do
true -> node_ids ++ [ id ]
false -> node_ids ++ [ id, inner_ids ]
end
false -> node_ids
end
nodes( terminate_id, tail, body, concat_node_ids )
end
def nodes( _terminate_id, [], _body, node_ids ), do: node_ids
#4の裏話や解説など
lib/Relation.exですが、「_」付きの引数が多用されています
これは、引数としては受け取るけど、後続で利用しないので、未使用でも
warning出さないでね、というコンパイラへの指示となります
ループ元データと、連結作成されるリスト (文字列) 以外の3つ以上の引数
を持つような再帰処理の終端関数でちょくちょく使うケースが多いです
- 9. 8
#4の裏話や解説など
同じくlib/Relation.exですが、戻り値をリスト([~]) で受け取る、という
Elixirならではの独特の表記があります
これは、戻り値として、「余計なリスト」で包まれて返ってくるようなケースにて、
その余計なリストを除外するためのテクニックです
Enum.mapは、余計なリストを付ける代表です
defmodule Relation do
…
def nodes( terminate_id, [ %{ "chunk" => %{ "id" => id, "link" => link } } | tail ], body, node_ids ) do
concat_node_ids = case terminate_id == [ link ] do
true ->
inner_ids = case link == "-1" do
true -> []
false ->
[ ids ] = Enum.map( [ id ], &( nodes( [ &1 ], body, body, [] ) ) )
ids
end
case inner_ids == [] do
true -> node_ids ++ [ id ]
false -> node_ids ++ [ id, inner_ids ]
end
false -> node_ids
end
nodes( terminate_id, tail, body, concat_node_ids )
end
def nodes( _terminate_id, [], _body, node_ids ), do: node_ids