views:

134

answers:

1

Im trying to solve Problem 11 of Project Euler in haskell. I almost did it, but right now im stuck, i want to transform a Matrix represented as [String] to a Matrix represented as [[Int]].

I "drawed" the matrices:

What i want:

"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]]

Im stuck in doing the last transformation (??a)


for curiosity(and learning) i also want to know how to do a matrix of digits:

Input:

"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] ]

What is the best way to make (??a) and (??b) ?

+4  A: 

What you want is the read function:

read :: (Read a) => String -> a

This thoughtfully parses a string into whatever you're expecting (as long as it's an instance of the class Read, but fortunately Int is such).

So just map that over the words, like so:

parseMatrix :: (Read a) => String -> [[a]]
parseMatrix s = map (map read . words) $ lines s

Just use that in a context that expects [[Int]] and Haskell's type inference will take it from there.

To get the digits, just remember that String is actually just [Char]. Instead of using words, map a function that turns each Char into a single-element list; everything else is the same.

camccann
Thanks! It solves the problem.(Is it possible to write in function composition? (something like map.map?)
Alessandro Stamatto
Yes, both "??a" and "??b" are equal to `(map.map) read`. The top transition in full is `map (map read . words) . lines` and the bottom one is `(map . map) (read . (:[])) . lines`.
Yitz
Woa, that's cool. Thanks!
Alessandro Stamatto