简体   繁体   中英

Haskell Let/In in main function

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?

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.

When you use let binding in a do block, don't 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM