gpt4 book ai didi

haskell - 在 Haskell 中将字符串转换为整数/ float ?

转载 作者:行者123 更新时间:2023-12-02 11:38:51 25 4
gpt4 key购买 nike

data GroceryItem = CartItem ItemName Price Quantity | StockItem ItemName Price Quantity

makeGroceryItem :: String -> Float -> Int -> GroceryItem
makeGroceryItem name price quantity = CartItem name price quantity

I want to create a `GroceryItem` when using a `String` or `[String]`

createGroceryItem :: [String] -> GroceryItem
createGroceryItem (a:b:c) = makeGroceryItem a b c

输入的格式为["Apple","15.00","5"],我使用Haskell的words函数将其分解。

我收到以下错误,我认为这是因为 makeGroceryItem 接受 FloatInt

*Type error in application
*** Expression : makeGroceryItem a read b read c
*** Term : makeGroceryItem
*** Type : String -> Float -> Int -> GroceryItem
*** Does not match : a -> b -> c -> d -> e -> f*

但是如何分别使 bc 类型为 FloatInt 呢?

最佳答案

read可以将字符串解析为float和int:

Prelude> :set +t
Prelude> read "123.456" :: Float
123.456
it :: Float
Prelude> read "123456" :: Int
123456
it :: Int

但是问题 (1) 出在您的模式中:

createGroceryItem (a:b:c) = ...

这里 : 是一个(右关联)二元运算符,它将一个元素添加到列表中。元素的 RHS 必须是列表。因此,给定表达式 a:b:c,Haskell 将推断出以下类型:

a :: String
b :: String
c :: [String]

c 将被视为字符串列表。显然它不能读取或传递到任何需要字符串的函数中。

相反,你应该使用

createGroceryItem [a, b, c] = ...

如果列表必须恰好有 3 个项目,或者

createGroceryItem (a:b:c:xs) = ...

如果≥3个项目是可以接受的。

还有 (2) 表达式

makeGroceryItem a read b read c

将被解释为带有 5 个参数的 makeGroceryItem,其中 2 个是 read 函数。您需要使用括号:

makeGroceryItem a (read b) (read c)

关于haskell - 在 Haskell 中将字符串转换为整数/ float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2468410/

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