如何解决关于 IO 的 Haskell 练习

How to solve a Haskell exercise about IO

我已经通过在一些讲师网站上找到的一些练习自学了 Haskell 几个月,我偶然发现了这个,但不知道如何解决它。

有两个任务有点 "connected"。我很轻松地解决了第一个问题,但不太了解如何解决另一个问题。

这是第一个:

Exercise 2. (Recall IO programming in Haskell and the do notation)

Write a recursive function

sumInts :: Integer -> IO Integer

that repeatedly reads integer numbers from IO until the number 0 is given. 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.

我是这样解决的:

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

这很容易做到。这是另一个,我无法理解的一个:

Exercise 3. Generalize the previous IO interaction into a higher order function

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. Check that for some values of getIO, condF, foldF, we can redefine sumInts as

sumInts = whileIO getIO condF foldF

希望在这方面得到一些帮助。 :)

提示:

尝试概括您的代码,将其片段作为参数而不是硬编码。例如,将 getInt 替换为更通用的 getIO 参数。

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

然后用通用谓词替换 x==0

然后使用通用折叠函数替换 (x+)

以此类推

最后你会得到想要的whileIO,你也可以给它一个练习建议的更通用的类型。