sortBy和interact一起工作相互协作吗?
这是我的代码中的一个片段:
io f = interact (unlines . f . lines)
io (sortBy compare (read :: String -> Int))
所以我读取这些行,获取数值,然后按它们排序。愿意引导我走上正确的道路吗?
here's a snip from my code:
io f = interact (unlines . f . lines)
io (sortBy compare (read :: String -> Int))
so I read the lines, get the numeric value, and sort by them. Care to guide me in the right path?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
Data.Ord
模块中的comparing
而不是compare
:You need to use
comparing
from theData.Ord
module instead ofcompare
:也许我不太明白你的问题,但这就是我得到它的方法:
函数
interact
将来自stdin
的输入输入到你的程序中,并将结果放入标准输出
。使用lines
和unlines
,您可以得到按行分割的输入和输出,因此您可以实际在该层上进行操作。您的函数 io 现在除了将函数 f 放入此框架之外什么也不做。接下来,
sortBy Compare
只不过是sort
。所以你基本上将行转换为数字并以这种方式对它们进行排序。结果是一个数字列表。您可能已经注意到,您的程序此时无法进行类型检查,因为unlines
需要[String]
而不是[Int]
输入。将函数更改为map show $sort (read :: String -> Int)
来解决此问题。我实际上会编写map show $ sort (asTypeOf 0 . read) 来代替,使其成为
Integer而不是
Int`并且更具可读性。Maybe I don't really understand your question, but this is how I got it:
The function
interact
feeds the input fromstdin
into your program and puts the result tostdout
. Usinglines
andunlines
, you get both the input and output split by lines, so you can actually operate on this layer. Your functionio
now does nothing else then putting the functionf
into this framework.Next,
sortBy compare
is nothing else thansort
. So you basically convert the lines to numbers and sort them this way. The result is a list of numbers. You may have noticed, that your program fails to typecheck at this point, asunlines
expects a[String]
and not a[Int]
for the input. Change your function tomap show $ sort (read :: String -> Int)
to fix this. I would actually writemap show $ sort (asTypeOf 0 . read) instead, making it an
Integerinstead of an
Int` and more readable.