簡體   English   中英

從模塊內部的 elixir 函數返回值

[英]Returning values from elixir functions inside modules

這是處理輸入字符串的方法

def process(input) do
    list=String.split(input, "\n")

    f3=fn(a) ->
            String.split(a," ")
    end

    list=Enum.map(list, f3)

    func3=fn(n) ->
            length(n)==3
    end

    func2=fn(n) ->
            length(n)<=2
    end

    system=for x <-list, func3.(x), do: x

    input=for y <- list, func2.(y), do: y

    input=Enum.slice(input,0..length(input)-2)

    output=""

    output(input,output, system)
  end

這是使用遞歸編輯字符串並最終返回其值的 output function

def output(input, output, system) do
    cond do
      length(input)==0 ->
        output
      true ->
        [thing|tail]=input

        if length(thing)==2 do
          output=output<>"From "<>Enum.at(thing, 0)<>" to "<>Enum.at(thing,1)<>" is "<>Integer.to_string(calculate(thing, system))<>"km\n"
          output(tail, output, system)
        end

        if length(thing)==1 do
          if Enum.at(thing,0)=="Sun" do
                  output=output<>"Sun orbits"
                  output(tail, output, system)
          else
                  output=output<>orbits(thing, system)<>" Sun"
                  output(tail, output, system)
          end
        end

        output(tail, output, system)
    end
  end

如您所見,當輸入為空列表時,它應該返回 output 字符串。 使用檢查顯示 output 字符串確實具有正確的值。 然而,當在 process() 中調用 function 時,它只返回空字符串,即 nil。

感謝任何幫助,我是 elixir 的新手,如果我的代碼有點混亂,我們深表歉意。

在這種情況下,在 function 標頭中使用模式匹配可以讓您基本上避免所有條件。 您可以將其分解為:

def output([], message, _) do
  message
end

def output([[from, to] | tail], message, system) do
  distance = Integer.to_string(calculate(thing, system))
  new_message = "#{message}From #{from} to #{to} is #{distance} km\n"
  output(tail, new_message, system)
end

def output([["Sun"] | tail], message, system) do
  output(tail, "Sun orbits #{message}", system)
end

def output([[thing] | tail], message, system) do
  new_message = "#{message}#{orbits([thing], system)} Sun"
  output(tail, new_message, system)
end

這解決了評論中突出顯示的一些困難:在塊內重新分配output沒有效果,並且沒有非本地返回,所以在if... end塊完成並繼續下一個條件,其結果丟失。 這也會捕獲一些不正確的輸入,如果輸入列表中出現空列表或 3 元素列表,您的進程將退出並出現模式匹配錯誤。

我已將output參數重命名為output function 到message 這不是必需的——無論您是否更改它,代碼都可以正常工作——但我發現通過 function 閱讀有點混亂,無論output是 function 調用還是變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM