Welcome to OGeek Q&A 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...