【问题标题】:Read strings as ints haskell将字符串读取为 ints haskell
【发布时间】:2013-12-07 02:33:00
【问题描述】:

无论如何我可以将字符串读取为整数吗?

例如阅读

triangle = ["1"
           ,"2 3"
           ,"4 5 6"]

作为[[1],[2,3],[4,5,6]]

convertToInt :: [String] -> [[Int]]
convertToInt [] = []
convertToInt (x:xs) = **(somehow convert x to list of ints)** : convertToInt xs

不知道如何进行,是否有任何内置函数?

编辑:谢谢!这是解决方案

convertToInt :: [String] -> [[Int]]
convertToInt [] = []
convertToInt (x:xs) = (map read (words x)) : convertToInt xs

【问题讨论】:

标签: haskell


【解决方案1】:

这里有一个提示让你开始

>> let str = "1 2 3"
>> words str
["1","2","3"]
>> map read (words str) :: [Int]
[1,2,3]

编辑

既然你现在已经知道你需要做什么,我想向你展示另一个解决方案,这可能会让你对 Haskell 有更多的思考

convertToInt :: [String] -> [[Int]]
convertToInt = map (map read . words)

试着弄清楚它是如何工作的——你对 Haskell 的理解会大大提高。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 2020-03-24
    • 2013-02-13
    • 2018-08-07
    • 2012-03-28
    • 1970-01-01
    相关资源
    最近更新 更多