list - 如何 List.sum 一个列表(也许是 float )?

我正在尝试将字符串转换为 float 并求出它们的总和:

> String.split "," "0.2,0.3,3.1" 
> List.map String.toFloat ["0.2","0.3","3.1"]
> List.sum [Just 0.2,Just 0.3,Just 3.1]

但我收到了这些编译器消息:

This argument is a list of type:

    List (Maybe Float)

But `sum` needs the 1st argument to be:

    List number

Hint: Use Maybe.withDefault to handle possible errors. Longer term, it is
usually better to write out the full `case` though!

我怎样才能得到这些值的总和?

最佳答案

您已经创建了一个List (Maybe Float),但是您需要一个List Float(number 是一种特殊类型,可以是IntFloat)。这意味着您需要处理列表中的值为 Nothing 的情况。错误消息建议使用 Maybe.withDefault,它看起来像这样:

"0.2,0.3,3.1"
|> String.split ","
|> List.map String.toFloat
|> List.map (Maybe.withDefault 0)
|> List.sum

或者,List.filterMap旨在接受一个返回 Maybe 并删除 Nothing 值的函数。在这种情况下,String.toFloat 就是那种函数,因此您可以改为:

"0.2,0.3,3.1"
|> String.split ","
|> List.filterMap String.toFloat
|> List.sum

https://stackoverflow.com/questions/63025226/

相关文章:

javascript - 如何为 Angular Material Slide Toggle 设置默

javascript - 将变量传递给自定义 Svelte Web 组件

javascript - 在嵌套导航器中导航时未定义 route.params?

python - GoogleTrans Python 不翻译

python - 属性错误 : 'list' object has no attribute 'en

python - matplotlib plt.ylim 引发错误列表对象不可调用

reactjs - React Native 删除 Flatlist 中的底部空间

python - 如何在python中解析html表格

reactjs - 避免在组件加载时对组件使用多个 useEffect

r - 拆分字符串、标记子字符串并将标记转换为数字向量