【问题标题】:Write an Erlang function called sort_of_sum that takes one argument List. The function should behave as follows:编写一个名为 sort_of_sum 的 Erlang 函数,它接受一个参数 List。该函数的行为应如下所示:
【发布时间】:2021-05-15 11:12:29
【问题描述】:

编写一个名为 sort_of_sum 的 Erlang 函数,它接受一个参数 List。该函数的行为应如下所示:

(使用模式匹配来解决这个问题。)

  • 如果 List 是一个没有元素的列表,则打印“There is nothing there!”
  • 如果 List 是一个包含一个元素的列表,则打印“The sum is sum”。其中 sum 是元素。
  • 如果 List 是一个包含两个元素的列表,则打印“The sum is sum”。其中 sum 是两个元素的总和。
  • 如果 List 是一个包含三个元素的列表,则打印“The sum is sum”。其中 sum 是三个元素的总和。
  • 如果 List 是一个包含三个以上元素的列表,则打印“That's too many to add!”提示:您可能需要使用 tail 构造 |以某种方式匹配这个。
  • 如果 List 是其他内容,请打印“I can't add that!”

【问题讨论】:

  • 你试过什么?它是如何失败的?
  • -模块(主)。 -出口([sort_of_sum/1])。 sort_of_sum(List=[]) -> io:format('那里什么都没有!~s~n',[List]); sort_of_sum([H|_]) -> sum = H , io:format('The sum is ~s~n',[sum]).
  • 不要将代码粘贴到评论中。请更新您的问题。
  • 我也是 Erlang 的新手,所以我尝试分段进行
  • 模式匹配就是“分块做”。

标签: erlang pattern-matching


【解决方案1】:

使用~w 来格式化整数,而不是~s。你在正确的轨道上。

-module(main).
-export([sort_of_sum/1]).

sort_of_sum([]) ->
    io:format("There is nothing there!~n");
sort_of_sum([H]) ->
    io:format("The sum is ~w.~n", [H]);
sort_of_sum([H1, H2]) ->
    io:format("The sum is ~w.~n", [H1 + H2]);
sort_of_sum([H1, H2, H3]) ->
    io:format("The sum is ~w.~n", [H1 + H2 + H3]);
sort_of_sum([_H | _T]) ->
    io:format("That's too many to add!~n");
sort_of_sum(_) ->
    io:format("I can't add that!~n").

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多