V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
themoment
V2EX  ›  Erlang

关于 erlang 的 io:format 函数使用问题:“列表变量” 和 “列表参数”

  •  
  •   themoment · 112 天前 · 494 次点击
    这是一个创建于 112 天前的主题,其中的信息可能已经有所发展或是发生改变。

    场景如下:

    Eshell V12.2.1  (abort with ^G)
    1> A1=[1,2,3].
    [1,2,3]
    2> io:format("~p~n", A1).
    ** exception error: bad argument
         in function  io:format/2
            called as io:format("~p~n",[1,2,3])
            *** argument 1: wrong number of arguments
    3> A2=[[1,2,3]].
    [[1,2,3]]
    4> io:format("~p~n", A2).
    [1,2,3]
    ok
    5> 
    

    疑问:

    难道 io:format 直接打印变量参数的话,需要变量是嵌套列表?求老司机解惑为什么要这样设计(本人 erlang 新手)。

    如果直接在调用 io:format 的时候,给参数传递一个列表参数的表达式也就不会报错。

    https://stackoverflow.com/questions/2523250/erlang-ioformat-and-a-hanging-web-application 这里我 google 到的一个疑问解答,但还是有些不明白 io:format 调用的时候,传递变量参数和列表表达式的区别。

    ifsclimbing
        1
    ifsclimbing  
       112 天前
    好的,看起来你在 Erlang 代码中遇到了一个错误。让我解释一下发生了什么。

    在 Erlang 中,当你使用`io:format/2`函数并带有“~p”格式说明符时,它期望一个单一的参数,而不是一个列表。当你尝试使用`io:format("~p~n", A1).`时,它把列表`[1,2,3]`视为三个单独的参数,从而导致错误。

    另一方面,当你用`A2=[[1,2,3]].`给`A2`赋了一个嵌套列表,然后使用`io:format("~p~n", A2).`时,它正常工作,因为嵌套列表被视为单个参数。

    如果你想使用`io:format/2`打印列表`[1,2,3]`,你应该将列表展平,或者使用`~w`格式说明符,它可以处理列表:

    ```erlang
    A1 = [1, 2, 3],
    io:format("~w~n", [A1]).
    ```

    这应该会打印:

    ```
    [1,2,3]
    ```

    或者,你可以展平列表:

    ```erlang
    A1 = [1, 2, 3],
    io:format("~p~n", [lists:flatten(A1)]).
    ```

    这也会打印:

    ```
    [1,2,3]
    ```
    ifsclimbing
        2
    ifsclimbing  
       112 天前
    来自 GPT 哈哈

    兄弟用 elixir 不

    https://elixir-lang.org/
    themoment
        3
    themoment  
    OP
       111 天前
    @ifsclimbing 感谢,大概明白了。还没有去了解 elixir ,目前在看 erlang
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1665 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 16:46 · PVG 00:46 · LAX 09:46 · JFK 12:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.