Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Let/In in main function

Tags:

haskell

My code:

import System.IO

main :: IO()
main = do
inFile <- openFile "file.txt" ReadMode
content <- hGetContents inFile
let
    someValue = someFunction(content)
    in
    print(anotherFunction(someValue))
    print(anotherFunction2(someValue))
hClose inFile

My error:

- Type error in application
*** Expression     : print (anotherFunction2(someValue))
*** Term           : print
*** Type           : e -> IO ()
*** Does not match : a -> b -> c -> d

I need to print two or more lines with functions that require "someValue". How I can fix it?

like image 360
JNo Avatar asked Dec 06 '22 11:12

JNo


1 Answers

The cause of that error message is that when you write

let
    someValue = someFunction(content)
    in
    print(anotherFunction(someValue))
    print(anotherFunction2(someValue))

the two print statements are actually parsed as one:

print (anotherFunction (someValue)) print (anotherFunction2 (someValue))

In other words, it thinks the second print as well as (anotherFunction2 (someValue)) are also arguments to the first print. This is why it complains that e -> IO () (the actual type of print) does not match a -> b -> c -> d (a function taking three arguments).

You can fix this by adding a do after the in to make it parse the two statements as separate:

let
    someValue = someFunction(content)
    in do
    print(anotherFunction(someValue))
    print(anotherFunction2(someValue))

Though, it's better to use the do-notation form of let here, without any in:

import System.IO

main :: IO()
main = do
    inFile <- openFile "file.txt" ReadMode
    content <- hGetContents inFile
    let someValue = someFunction content
    print (anotherFunction someValue)
    print (anotherFunction2 someValue)
    hClose inFile

I also got rid of some redundant parentheses in the above code. Remember, they are only used for grouping, not for function application in Haskell.

like image 163
hammar Avatar answered Dec 09 '22 15:12

hammar