2
votes

what's the preferred idiomatic way of reading files in Idris? For example I'm trying to read numbers from a file map that to Int values and sum everything. Input file

5 3 4 6 12

import Data.String

myCast: Maybe Integer -> Integer
myCast Nothing = 0
myCast (Just val) = val


sumNums: String -> Integer
sumNums s = sum (map myCast (map parseInteger (words s)))

and I'm interested mostly in the reading part

main : IO ()
main = do
  (Right content) <- readFile "input.txt" | (Left err) => printLn err
  printLn (sumNums content)

What is the proper way to deal with Either / Maybe here?

1

1 Answers

1
votes

From the book and the docs

main : IO ()
main = do file <- readFile "input.txt"
          case file of
               Right content => printLn (sumNums content)
               Left err => printLn err

the <- allows us to act directly on the Either of the IO (Either FileError String). We then case split on the possible values, printing them in each case