带有条件的 Haskell 中的 while 循环 [英] While loop in Haskell with a condition
问题描述
我在这里遇到了一些 Haskell 情况.我正在尝试用 monad 编写两个函数.只要函数的输入/输出条件为真,第一个就应该遍历一个函数.第二个应该使用第一个将数字作为输入并将其作为输出写入,直到您输入空格.
I'm having a little Haskell Situation over here. I'm trying to write two functions with monads. First one is supposed to iterate through a function as long as the condition is true for the input / output of the function. Second one is supposed to use the first one to take a number as input and write it as output until you enter a space.
我遇到了这个问题,有什么帮助吗?
I'm stuck with this, any help?
module Test where
while :: (a -> Bool) -> (a -> IO a) -> a -> IO a
while praed funktion x = do
f <- praed (funktion x)
if f == True then do
y <- funktion x
while praed funktion y
else return x
power2 :: IO ()
power2 = do putStr (Please enter a number.")
i <- getChar
while praed funktion
where praed x = if x /= ' ' then False else True
funktion = i
推荐答案
import Control.Monad
while :: (a -> Bool) -> (a -> IO a) -> a -> IO a
while praed funktion x
| praed x = do
y <- funktion x
while praed funktion y
| otherwise = return x
power2 :: IO ()
power2 = do
putStr "Please enter a number."
i <- getChar
let praed x = x /= ' '
let f x = do
putChar x
getChar
while praed f '?'
return ()
一些注意事项:
- 使用
if x then True else False
是多余的,它等同于x
. - 类似地,
if x == True ...
是多余的,等同于if x ...
. 您需要区分
IO
操作及其结果.例如,如果你这样做
- Using
if x then True else False
is redundant, it's equivalent to justx
. - Similarly
if x == True ...
is redundant and equivalent toif x ...
. You need to distinguish between
IO
actions and their results. For example, if yo do
do
i <- getChar
...
then in ... i
代表动作的结果,一个字符,所以i :: Char
.但是 getChar :: IO Char
是动作本身.您可以将其视为执行时返回 Char
的配方.您可以将配方传递给函数等,并且只有在某处执行时才会执行.
then in ... i
represents the result of the action, a character, so i :: Char
. But getChar :: IO Char
is the action itself. You can view it as a recipe that returns Char
when performed. You can pass the recipe around to functions etc., and it is only performed when executed somewhere.
你的 while
调用了 funktion
两次,这可能不是你想要的 - 它会读取一个字符两次,检查第一个并返回第二个一.请记住,您的 funktion
是一个动作,因此每次您调用"该动作时(例如通过在 do<中使用
<- funktion ...
/code> 符号),动作再次运行.所以它应该像
Your while
called funktion
twice, which probably isn't what you intend - it would read a character twice, check the first one and return the second one. Remember, your funktion
is an action, so each time you "invoke" the action (for example by using <- funktion ...
in the do
notation), the action is run again. So it should rather be something like
do
y <- funktion x
f <- praed y
-- ...
(我的代码有些不同,它检查传递给它的参数.)
(My code is somewhat different, it checks the argument that is passed to it.)
这篇关于带有条件的 Haskell 中的 while 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!