简体   繁体   中英

Haskells stack or interact are adding characters

I'm doing my first steps using Haskell. I created a project using stack and changed the Main.hs into

module Main where

my_fkt :: String -> String
my_fkt input = show (length input)

main :: IO ()
main = interact my_fkt

I build the project via stack build , run it via stack exec firststeps-exe , enter "abcd" and finish input via <CTRL>-D . In the console I now see

abcd4%

The % is inverted. If I use a text file containing the "abcd" (without line break) and execute more sample.txt | stack exec firststeps-exe more sample.txt | stack exec firststeps-exe I see

abcd5%

Why do I get one additional character in the second case and what is the inverted percentage sign?

That is because the definition of interact uses putStr instead of putStrLn .

You can take a look at the source code here .

 interact :: (String -> String) -> IO () interact f = do s <- getContents putStr (fs) 

To remedy your issue I would go on and create a similar function

interact' :: (String -> String) -> IO ()
interact' f = do s <- getContents
                putStrLn (f s)

or if you like to mix it up and write a bit terser code

interact' f = putStrLn =<< (f <$> getContents)

I don't know what the % is or why it is showing up, my guess would be that it is the escaped CTRL-D .

With regards to your second question about the additional "non-existing" character, I am also not sure, but here my guess would be that this is the \\EOF .

Btw. you can always check using more testinput | wc -c more testinput | wc -c it should yield the same result as your haskell program.

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