【问题标题】:Elm - mapping a list and appending string to the end of each itemElm - 映射列表并将字符串附加到每个项目的末尾
【发布时间】:2018-01-10 15:50:39
【问题描述】:

我正在学习 Elm 并试图了解如何将字符串附加到列表中的所有项目,但在每个条目的末尾而不是开头。很抱歉提出 n00b 问题,但我已经阅读了有关 List.map、String (.append、.join) 的所有文档/示例,但似乎找不到答案。

例如

--create username list
usernames = ["Dave", "Simon", "Sally", "Joe"]    

--create confirmExit function
confirmExit name = String.append " has left the room" name

--apply confirmExit function to all items in username list
List.map (\x -> confirmExit x) usernames

给我:

["has leftDave","has leftSimon","has leftSally","has leftJoe"] : List String

但是我该如何让它返回:

["Dave has left","Simon has left","Sally has left","Joe has left"] : List String

是否有一个等效的 .append 添加到末尾而不是开头?请问?!

【问题讨论】:

  • 建议改进:由于\x -> confirmExit xconfirmExit 功能相同,请在List.map 调用中直接使用confirmExitList.map confirmExit usernames

标签: elm


【解决方案1】:

你只是把参数颠倒了,试试:

confirmExit name = String.append name " has left the room"

来自docs

追加:字符串->字符串->字符串

附加两个字符串。你也可以 使用 (++) 运算符来执行此操作。

append "butter" "fly" == "butterfly"

所以你也可以使用:

confirmExit name = name ++ " has left the room"

这可能更具可读性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-15
    • 2016-07-20
    • 2022-12-11
    • 2017-12-19
    • 2020-08-19
    • 2014-03-06
    • 2017-09-29
    • 2021-10-06
    相关资源
    最近更新 更多