Convert String to Integer/Float in Haskell?
Solution 1:
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
But the problem (1) is in your pattern:
createGroceryItem (a:b:c) = ...
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]
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.
Instead you should use
createGroceryItem [a, b, c] = ...
if the list must have exactly 3 items, or
createGroceryItem (a:b:c:xs) = ...
if ≥3 items is acceptable.
Also (2), the expression
makeGroceryItem a read b read c
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)
Solution 2:
Even though this question already has an answer, I strongly suggest using reads
for string conversion, because it's much safer, as it does not fail with an unrecoverable exception.
reads :: (Read a) => String -> [(a, String)]
Prelude> reads "5" :: [(Double, String)]
[(5.0,"")]
Prelude> reads "5ds" :: [(Double, String)]
[(5.0,"ds")]
Prelude> reads "dffd" :: [(Double, String)]
[]
On success, reads
returns a list with exactly one element: A tuple consisting of the converted value and maybe unconvertable extra characters. On failure, reads
returns an empty list.
It's easy to pattern-match on success and failure, and it will not blow up in your face!