Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Daniel Wagner's solution is a great one. Here is another swing at it so you can get some more ideas about efficient file handling.</p> <pre><code>{-# LANGUAGE OverloadedStrings #-} import System.IO import qualified Data.ByteString.Lazy.Char8 as B import Control.Applicative import Data.List sumNums :: B.ByteString -&gt; Int sumNums s = foldl' sumStrs 0 $ B.split ' ' s sumStrs :: Int -&gt; B.ByteString -&gt; Int sumStrs m i = m+int where Just(int,_) = B.readInt i main = do sums &lt;- map sumNums &lt;$&gt; B.lines &lt;$&gt; B.readFile "testy" print sums </code></pre> <p>First, you'll see the OverloadedStrings pragma. This allows use to just use normal quotes for string literals that are actually bytestrings. We will be using Lazy ByteStrings for processing the file for several reasons. First, it allows us to stream the file through the program rather than forcing it all into memory at once. Also, bytestrings are faster and more efficient than strings in general. </p> <p>Everything else is pretty much straightforward. We readFile the file into a lazy list of lines, and then map a summing function over each of the lines. The <code>&lt;$&gt;</code> are just shortcuts to allow us to operate on the value inside of IO() functor -- if this is too much I apologize. I just mean that when you readFile you don't get back a ByteString, you get back a ByteString wrapped in IO an IO(ByteString). The <code>&lt;$&gt;</code> says "Hey' I want to operate on the thing inside the IO and then wrap it back up.</p> <p>B.split separates each line into numbers based on whitespace. (We could also use B.words for this) The only other interesting part is the in <code>sumStrs</code> we use deconstruction/pattern matching to extract the first value out of the Just that is returned by the readInt function.</p> <p>I hope this was helpful. Ask if you have any questions.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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