如何在像haskell这样的函数式语言中模拟while循环? [英] How can a while loop be simulated in a functional language like haskell?

查看:244
本文介绍了如何在像haskell这样的函数式语言中模拟while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Haskell中使用while循环。

代码示例会很棒。



how to use while loop in Haskell.
Code example would be great.

how to use while loop in Haskell.
Code example would be great.







how to use while loop in Haskell.
Code example would be great.





我尝试过:





What I have tried:

how to use while loop in Haskell.
Code example would be great.







how to use while loop in Haskell.
Code example would be great.







how to use while loop in Haskell.
Code example would be great.

推荐答案

我不知道Haskell,但有一件事应该仍然是对函数式语言有效:迭代(循环)总是可以用等效的递归替换,反之亦然。



recursion [ ^ ]是一个自我调用的函数。每个调用代表原始循环的迭代。无限递归不起作用(它通常以堆栈溢出结束),因此必须有一些条件终止递归并简单地返回。



对于'while类型'递归,你必须测试你的条件,以决定执行你的功能或返回。这是类似C的伪代码:



I don't know Haskell, but there is one thing that should still be valid for a functional language: Iteration (loops) can always be replaced by an equivalent recursion or vice versa.

The least confusing definition of recursion[^] is a function that calls itself. Each call represents an iteration of the original loop. Endless recursion does not work (it usually ends in a stack overflow), therefore there must be some condition that ends the recursion and simply returns.

For a 'while type' recursion, you would have to test your condition in order to decide wether to execute your function or to return. This is C-like pseudocode:

ReturnType RecursiveFunction(SomeParameters)
{
    if(Condition == true)
    {
        return;
    }
    else
    {
        // Do whatever your loop should have done,
        // possibly modifying the parameters that have been passed.

        // recursive call to your function
        return RecursiveFunction(ModifiedParameters);
    }
}





也许这个链接可以提供帮助:

递归 - 为了一个很好的学习你的Haskell! [ ^ ]


这篇关于如何在像haskell这样的函数式语言中模拟while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆