Search code examples
haskellconditional-statementsparse-error

"parse error on input" in Haskell if-then-else conditional


The following do block throws the error "parse error on input `conn'" when I attempt to compile it. I have tried many different configurations of the if-then-else statement to no avail. The database logic worked before I added the conditional, so there isn't a problem with that. Do I have too many lines in the else? Is there any way to fix this without completely revamping the logic?

main = do
   contents <- BL.getContents
   let myData = decode contents :: Maybe Data
   if maybe True (\x -> result x /= "success") myData
      then error ("JSON download failed")
      else let myTrades = process myData
         conn <- connectSqlite3 "trades.db"
         insert <- DB.prepare conn "INSERT INTO trades VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);"
         DB.executeMany insert $ map (\xs -> map DB.toSql xs) myTrades
         DB.commit conn
         DB.disconnect conn

Solution

  • You need to introduce a do block after the else like so:

      else do let myTrades = process myData
              conn <- connectSqlite3 "trades.db"
              insert <- DB.prepare conn "INSERT INTO trades VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);"
              DB.executeMany insert $ map (\xs -> map DB.toSql xs) myTrades
              DB.commit conn
              DB.disconnect conn