Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

haskell - Converting the first element in a list of strings to an integer

the list is:

l = ["1","kg","g"]

I found this method but it didn't work:

    map (convert) l
    convert [x, "kg", "g"] = (read x :: Integer) *1000

I got the following error:

    parse error on input `='
    Perhaps you need a 'let' in a 'do' block?
    e.g. 'let x = 5' instead of 'x = 5'
   |
17 |     convert [x, "kg", "g"] = (read x :: Integer) *1000
   |                            ^                ^

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can not convert values with a typehint. Haskell has a strong type system, which means that you can only use functions to turn a String in an Integer for example.

Since Integer is an instance of the Read typeclass, you can use read :: Read a => String -> a to parse a string to an Integer:

convert [x, "kg", "g"] = (read x :: Integer) *1000

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...