简体   繁体   English

Haskells堆栈或交互正在添加字符

[英]Haskells stack or interact are adding characters

I'm doing my first steps using Haskell. 我正在使用Haskell做我的第一步。 I created a project using stack and changed the Main.hs into 我使用stack创建了一个项目,并将Main.hs更改为

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 . 我通过stack build构建项目,通过stack exec firststeps-exe运行它,输入“ abcd”并通过<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 如果我使用包含“ abcd”的文本文件(不带换行符)并执行more sample.txt | stack exec firststeps-exe more sample.txt | stack exec firststeps-exe I see 我看到的more sample.txt | stack exec firststeps-exe

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 . 这是因为interact的定义使用putStr而不是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 . 我不知道%是什么或为什么显示它,我的猜测是它是转义的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 . 关于您关于第二个“不存在”字符的第二个问题,我也不确定,但是我的猜测是这是\\EOF

Btw. 顺便说一句。 you can always check using more testinput | wc -c 您可以随时使用more testinput | wc -c检查more testinput | wc -c more testinput | wc -c it should yield the same result as your haskell program. more testinput | wc -c它应产生与haskell程序相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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