我试图在haskell中解决Problem 11 of Project Euler。我几乎做到了,但是现在我 卡住了,我想将表示为[String]的Matrix转换为表示为[[Int]]的矩阵。
我“绘制”了矩阵:
我想要的是什么:
"08 02 22 97 38 15 00 40 [ ["08","02","22","97","38","15","00","40"], [[08,02,22,97,38,15,00,40]
49 49 99 40 17 81 18 57 map words lines ["49","49","99","40","17","81","18","57"], ??a [49,49,99,40,17,81,18,57]
81 49 31 73 55 79 14 29 ----------> ["81","49","31","73","55","79","14","29"], ---------> [81,49,31,73,55,79,14,29]
52 70 95 23 04 60 11 42 ["52","70","95","23","04","60","11","42"], [52,70,95,23,04,60,11,42]
22 31 16 71 51 67 63 89 ["22","31","16","71","51","67","63","89"], [22,31,16,71,51,67,63,89]
24 47 32 60 99 03 45 02" ["24","47","32","60","99","03","45","02"] ] [24,47,32,60,99,03,45,02]]
我坚持做最后的转换(?? a)
为了好奇(和学习),我也想知道如何做一个数字矩阵:
输入:
"123456789 [ "123456789" [ [1,2,3,4,5,6,7,8,9]
124834924 lines "124834924" ??b [1,2,4,8,3,4,9,2,4]
328423423 ---------> "328423423" ---------> [3,2,8,4,2,3,4,2,3]
334243423 "334243423" [3,3,4,2,4,3,4,2,3]
932402343" "932402343" ] [9,3,2,4,0,2,3,4,3] ]
制作(?? a)和(?? b)的最佳方法是什么?
答案 0 :(得分:4)
你想要的是read
功能:
read :: (Read a) => String -> a
这会仔细地将字符串解析为您期望的任何内容(只要它是类Read
的实例,但幸运的是Int
就是这样。)
所以只需在单词上映射,就像这样:
parseMatrix :: (Read a) => String -> [[a]]
parseMatrix s = map (map read . words) $ lines s
只需在期望[[Int]]
的上下文中使用它,Haskell的类型推断将从那里获取它。
要获取数字,请记住String
实际上只是[Char]
。而不是使用words
,映射一个函数,将每个Char
转换为单个元素列表;其他一切都是一样的。