在 Haskell 中将字符串转换为整数/浮点数? [英] Convert String to Integer/Float in Haskell?
问题描述
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
函数将其分解.
The input will be in the format ["Apple","15.00","5"]
which I broke up using Haskell's words
function.
我收到以下错误,我认为这是因为 makeGroceryItem
接受 Float
和 Int
.
I get the following error which I think is because makeGroceryItem
accepts a Float
and an Int
.
*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*
但是我如何分别制作 Float
和 Int
类型的 b
和 c
?
But how do I make b
and c
of type Float
and Int
, respectively?
推荐答案
read
可以将字符串解析为 float 和 int:
read
can parse a string into float and int:
Prelude> :set +t
Prelude> read "123.456" :: Float
123.456
it :: Float
Prelude> read "123456" :: Int
123456
it :: Int
但问题 (1) 出在您的模式中:
But the problem (1) is in your pattern:
createGroceryItem (a:b:c) = ...
这里的 :
是一个(右结合)二元运算符,它将元素添加到列表中.元素的 RHS 必须是一个列表.因此,给定表达式 a:b:c
,Haskell 将推断出以下类型:
Here :
is a (right-associative) binary operator which prepends an element to a list. The RHS of an element must be a list. Therefore, given the expression a:b:c
, Haskell will infer the following types:
a :: String
b :: String
c :: [String]
即c
将被认为是一个字符串列表.显然它不能被 read
或传递给任何需要 String 的函数.
i.e. c
will be thought as a list of strings. Obviously it can't be read
or passed into any functions expecting a String.
相反,你应该使用
createGroceryItem [a, b, c] = ...
如果列表必须正好有 3 个项目,或者
if the list must have exactly 3 items, or
createGroceryItem (a:b:c:xs) = ...
如果 ≥3 个项目是可以接受的.
if ≥3 items is acceptable.
还有(2),表达式
makeGroceryItem a read b read c
将被解释为带有 5 个参数的 makeGroceryItem
,其中 2 个是 read
函数.您需要使用括号:
will be interpreted as makeGroceryItem
taking 5 arguments, 2 of which are the read
function. You need to use parenthesis:
makeGroceryItem a (read b) (read c)
这篇关于在 Haskell 中将字符串转换为整数/浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!