List.map String.toFloat ["0.2","0.3"-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:08:48 25 4
gpt4 key购买 nike

我正在尝试将字符串转换为 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

关于list - 如何 List.sum 一个列表(也许是 float )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63025226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com