Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I parse a matrix of integers in Haskell?
    text
    copied!<p>So I've read the theory, now trying to parse a file in Haskell - but am not getting anywhere. This is just so weird...</p> <p>Here is how my input file looks:</p> <pre><code> m n k1, k2... a11, ...., an a21,.... a22 ... am1... amn </code></pre> <p>Where m,n are just intergers, <code>K = [k1, k2...]</code> is a list of integers, and <code>a11..amn</code> is a "matrix" (a list of lists): <code>A=[[a11,...a1n], ... [am1... amn]]</code></p> <p>Here is my quick python version:</p> <pre class="lang-py prettyprint-override"><code>def parse(filename): """ Input of the form: m n k1, k2... a11, ...., an a21,.... a22 ... am1... amn """ f = open(filename) (m,n) = f.readline().split() m = int(m) n = int(n) K = [int(k) for k in f.readline().split()] # Matrix - list of lists A = [] for i in range(m): row = [float(el) for el in f.readline().split()] A.append(row) return (m, n, K, A) </code></pre> <p>And here is how (<strong>not very</strong>) far I got in Haskell:</p> <pre class="lang-hs prettyprint-override"><code>import System.Environment import Data.List main = do (fname:_) &lt;- getArgs putStrLn fname --since putStrLn goes to IO ()monad we can't just apply it parsed &lt;- parse fname putStrLn parsed parse fname = do contents &lt;- readFile fname -- ,,,missing stuff... ??? how can I get first "element" and match on it? return contents </code></pre> <p>I am getting confused by monads (and the context that the trap me into!), and the do statement. I really want to write something like this, but I know it's wrong:</p> <pre><code>firstLine &lt;- contents.head (m,n) &lt;- map read (words firstLine) </code></pre> <p>because contents is not a list - but a monad.</p> <p>Any help on the <em>next</em> step would be great.</p> <p>So I've just <a href="https://stackoverflow.com/questions/215748/haskell-inserting-every-line-from-a-file-into-a-list">discovered</a> that you can do:</p> <pre><code> liftM lines . readFile </code></pre> <p>to get a list of lines from a file. However, still the example only only transforms the ENTIRE file, and doesn't use just the first, or the second lines...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload