ListMultiplication

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
{-# LANGUAGE OverloadedStrings #-}

import System.Environment (getArgs)
import Data.Text (Text, splitOn, strip)
import qualified Data.Text as Text
import Data.Text.IO as IO
import Data.Text.Read
import Data.List (intercalate)

{-
    This program reads a file with |-separated lists:

    9 0 6 | 15 14 9
    5 | 8
    13 4 15 1 15 5 | 1 4 15 14 8 2

    and it returns each element of the left list multiplied with the elements of the right one:

    "135 0 54"
    "40"
    "13 16 225 14 120 10"

-}

textToInt :: Text -> Int
textToInt s = case decimal s of
    Right (i,_) -> i

textToInts :: Text -> [Int]
textToInts s = map textToInt (splitOn (" " :: Text) (strip s))

main = do
    [inpFile] <- getArgs
    input <- IO.readFile inpFile
    mapM_ (
        print .
        unwords .                   -- turn list into a single string
        map show .                  -- turn elements into strings
        (\listOfTwo -> zipWith (*) (head listOfTwo) (listOfTwo !! 1)) . -- zip with multiplication
        map textToInts .            -- "1 2 3" -> [1,2,3]
        splitOn (Text.pack "|")     -- first split at the |
        )
        (Text.lines input)