【问题标题】:Elixir - passing function parameter throughElixir - 传递函数参数
【发布时间】:2017-05-10 14:37:02
【问题描述】:

假设我有一个函数,它有点冗长并且每次都使用相同的参数调用,这个函数也需要做很多设置才能在其回调中调用该模块的任何其他函数。

SomeMod.called_a_lot(‘xx’, fn(y) ->
  SomeMod.needs_called_a_lot_to_be_called_first(‘do_stuff’)
end)

我想我可以这样包装它:

defp easier_to_call(func) do
  SomeMod.called_a_lot(‘xx’, fn(y) -> func(y) end
end

然后像这样使用它:

easier_to_call(fn(y) ->
  SomeMod.needs_called_a_lot_to_be_called_first(‘do_stuff’)
end)

实际上如何在 Elixir 中做到这一点?

【问题讨论】:

  • 你的代码看起来不错;只需将func(y) 更改为func.(y),因为它是一个匿名函数。

标签: elixir function-parameter


【解决方案1】:

您的语法对于调用匿名函数有点偏离。您将需要使用

func.(y)

而不是

func(y)

因为它是一个匿名函数。

有关简短示例,请参阅Elixir Crash Course

【讨论】:

    【解决方案2】:

    Dogbert 的评论是正确的。但由于您不修改参数,您可以直接传递函数而不将其包装在匿名函数中:

    defp easier_to_call(func) do
      SomeMod.called_a_lot(‘xx’, func)
    end
    

    【讨论】:

      【解决方案3】:

      我不太明白你到底在问什么,但我觉得capture operator (&) 就是你要找的东西。

      一个例子是:

      easier_func = &SomeMod.called_a_lot(‘xx’, &1)
      
      easier_func.(fn(_y) ->
        SomeMod.needs_called_a_lot_to_be_called_first(‘do_stuff’)
      end)
      

      &1 是匿名函数中的第一个参数。

      如果你需要一个多重匿名函数,那么你可以这样做:

      easy_reduce = &Enum.reduce(&1, 0, &2)
      
      easy_reduce.([1,2,3,4], fn(x, acc) -> acc + x end) # => 10
      

      【讨论】:

        【解决方案4】:

        只是为了展示另一种方法:它可以通过宏来实现,即先调用要调用的函数,然后调用块:

        defmodule Test do
          defmacro with_prepended(arg, do: block) do
            quote do
              IO.inspect(unquote(arg), label: "In function")
              prepended(unquote(arg))
              unquote(block)
            end
          end
        end
        
        defmodule Tester do
          require Test
        
          defp prepended(arg), do: IO.inspect(arg, label: "In prepended")
        
          def fun(arg) do
            Test.with_prepended(arg) do
              IO.puts "Actual code"
            end
          end
        end
        
        Tester.fun(42)
        
        #⇒ In function: 42
        #⇒ In prepended: 42
        #⇒ Actual code
        

        【讨论】:

          猜你喜欢
          • 2014-04-29
          • 1970-01-01
          • 2018-02-05
          • 2015-06-08
          • 1970-01-01
          • 1970-01-01
          • 2013-01-27
          • 2021-04-13
          • 1970-01-01
          相关资源
          最近更新 更多