如何使用回调正确管道(链)函数

时间:2016-04-21 06:03:06

标签: elixir

我正试着从我正在学习的这本书中做这个练习。

目标是从随机.txt文件(提供的)中读取一堆单词,然后查找以D开头的所有单词,并将这些单词大写并仅返回它们。这就是我到目前为止所做的:

defmodule ReadFile do
    def findD(contents) do
        newArray = Enum.filter(contents, (word -> String.starts_with?(word, "D")))
        |> Enum.map (word -> String.upcase(word))
    end
end

我觉得理论上这应该可行,但似乎并不好。任何信息都会非常棒。

我正试图以我在Elixir文档中找到它的方式使用Filter

filter(t, (element -> as_boolean(term))) :: list

这是我的错误:

listTest.exs:1: warning: redefining module ReadFile

== Compilation error on file listTest.exs ==
** (CompileError) listTest.exs:3: unhandled operator ->
    (stdlib) lists.erl:1353: :lists.mapfoldl/3
    (stdlib) lists.erl:1354: :lists.mapfoldl/3

** (exit) shutdown: 1
    (elixir) lib/kernel/parallel_compiler.ex:202: Kernel.ParallelCompiler.handle_failure/5
    (elixir) lib/kernel/parallel_compiler.ex:185: Kernel.ParallelCompiler.wait_for_messages/8
    (elixir) lib/kernel/parallel_compiler.ex:55: Kernel.ParallelCompiler.spawn_compilers/3
       (iex) lib/iex/helpers.ex:168: IEx.Helpers.c/2

1 个答案:

答案 0 :(得分:2)

你在函数语法中有一些错误,正确的是:

contents
|> Enum.filter(fn(word) -> String.starts_with?(word, "D") end)
|> Enum.map(fn(word) -> String.upcase(word) end)

另外,请阅读the getting started guide

相关问题