简体   繁体   English

使用 Haskell 中的交互从输入创建列表

[英]Create list from input using interact in Haskell

I'm starting out with Haskell and was looking into I/O mechanims.我从 Haskell 开始,正在研究 I/O 机制。 I read up on the interact function which takes a function of type String -> String as parameter.我阅读了交互函数,该函数采用 String -> String 类型的函数作为参数。 I tried to write a simple program that takes to numbers from stdin and creates a list and prints it line by line.我试图编写一个简单的程序,它从标准输入中获取数字并创建一个列表并逐行打印。

import Data.List

readIn = sort . map read . words 
writeOut = unlines . map show
rangeList [n,m] = [n .. m] 
main = interact (writeOut . rangeList . readIn)

For some reason it wont print the numbers.出于某种原因,它不会打印数字。 Could you help me out?你能帮我吗?

interact requires you to input an end-of-file (EOF) to stdin with Ctrl + D (or Ctrl + Z on Windows); interact要求您使用Ctrl + D (或 Windows 上的Ctrl + Z )将文件结尾 (EOF) 输入到标准输入; when I type that combination, the output appears as required.当我键入该组合时,输出将按要求显示。 This is necessary because, as the documentation for interact states, 'the entire input from the standard input device is passed to [interact] as its argument';这是必要的,因为作为interact状态的文档,“来自标准输入设备的整个输入作为其参数传递给 [interact]”; due to this, you need to explicitly signal the place where stdin ends.因此,您需要明确表示 stdin 结束的位置。

(By the way, I'm not even sure how you got your program to compile; GHC gives me lots of 'ambiguous type' errors when I try. I had to add type signatures to get it working, at which point I found the solution above to work.) (顺便说一句,我什至不确定你是如何编译你的程序的;当我尝试时,GHC 给了我很多“模棱两可的类型”错误。我不得不添加类型签名才能让它工作,此时我发现了上面的解决方案工作。)

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

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