简体   繁体   English

如何解决有关IO的Haskell练习

[英]How to solve a Haskell exercise about IO

I have been learning Haskell for few months on my own now by doing some exercises I found on some lecturers site, and I stumbled upon this one and cannot figure how to solve it. 现在,我通过做一些讲师网站上的练习,独自学习了Haskell几个月,但我偶然发现了这个问题,无法解决。

There are two tasks that are kinda "connected". 有两个任务是“连接”的。 I solved the first one with ease, but don't really understand how to do the other one. 我很轻松地解决了第一个问题,但是并不太了解如何做另一个问题。

Here's the first one: 这是第一个:

Exercise 2. (Recall IO programming in Haskell and the do notation) 练习2。(回想一下Haskell中的IO编程和do表示法)

Write a recursive function 编写一个递归函数

 sumInts :: Integer -> IO Integer 

that repeatedly reads integer numbers from IO until the number 0 is given. 反复从IO读取整数,直到给出数字0。 At that point, the function should return the sum of all the entered numbers plus the original (default) value, which is given as a function parameter. 此时,函数应返回所有输入数字的总和加上原始(默认)值,该值作为函数参数给出。

I solved this one this way: 我这样解决了这个问题:

getInt :: IO Integer          
getInt = do  
  s <- getLine
  return (read s)


sumInts :: Integer -> IO Integer
sumInts input = do
  x<-getInt
  if x==0 then return input else (x+) <$> sumInts input

It was pretty easy to do. 这很容易做到。 Here's the other one, the one I cannot understand: 这是另一个,我无法理解的一个:

Exercise 3. Generalize the previous IO interaction into a higher order function 练习3.将以前的IO交互概括为一个高阶函数

 whileIO :: IO a -> (a -> Bool) -> (a -> a -> a) -> a -> IO a 

which, for the given reading IO action, termination condition, folding function, and the original value, returns the required IO action. 对于给定的读取IO操作,终止条件,折叠功能和原始值,它们将返回所需的IO操作。 Check that for some values of getIO, condF, foldF, we can redefine sumInts as 检查是否有一些getIO,condF,foldF值,我们可以将sumInts重新定义为

 sumInts = whileIO getIO condF foldF 

Would love some help with this one. 希望对此有所帮助。 :) :)

Hint: 暗示:

try to generalize your code, making pieces of it as parameters instead of hardcoding them. 尝试对您的代码进行泛化,将其片段作为参数,而不是对其进行硬编码。 For instance, replace the getInt with a more general getIO parameter. 例如,将getInt替换为更通用的getIO参数。

sumInts :: IO Integer -> Integer -> IO Integer
sumInts getIO input = do
    --  ^^^^^
  x<-getIO -- <------
  if x==0 then return input else (x+) <$> sumInts input

Then replace x==0 with a generic predicate. 然后将x==0替换为通用谓词。

Then replace (x+) using a generic folding function. 然后使用通用折叠功能替换(x+)

And so on. 等等。

At the very end you'll get the wanted whileIO , and you can also give it the more general type suggested by the exercise. 最后,您将获得所需的whileIO ,还可以为练习提供更通用的类型。

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

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