Haskell Let / In in the main function

My code is:

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 mistake:

 - 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 requiring "someValue". How can i fix this?

+4
source share
2 answers

When you use let binding in a do block, do not use the in keyword.

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

The reason for this error message is that when writing

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

two print statements are actually parsed as one:

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

In other words, he believes that the second print , as well as (anotherFunction2 (someValue)) are also arguments for the first print . That's why he complains that e -> IO () (the actual print type) does not match a -> b -> c -> d (the function takes three arguments).

You can fix this by adding do after in to parse these two statements as separate:

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

Although, it is better to use the do -notation of the let form 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 that they are used only for grouping, and not for applying functions in Haskell.

+8
source

Source: https://habr.com/ru/post/1445719/


All Articles