Haskell-for循环 [英] Haskell - for loop

查看:418
本文介绍了Haskell-for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想表达类似[只是一个简单的例子]:

if I want to express something like [just a simple example]:

int a = 0;
for (int x = 0; x < n; x += 1)
    a = 1 - a;

我在Haskell中应该做什么,因为它没有可变的概念?(可能是错误的,请参见:

what should I do in Haskell, since it doesn't have variable concept? (maybe wrong, see: Does Haskell have variables?)

推荐答案

通常,您将使用过程语言中的循环执行的重复操作是通过递归在Haskell中.在这种情况下,您应该考虑循环的结果.它似乎在0和1之间交替.在Haskell中,有几种方法可以做到这一点.一种方法是

Often, repetition that you would perform with a loop in a procedural language is accomplished with recursion in Haskell. In this case, you should think about what the result of the loop is. It appears to alternate between 0 and 1. There are several ways to do this in Haskell. One way is

alternatingList n = take n alternating0and1
alternating0and1 = 0 : alternating1and0
alternating1and0 = 1 : alternating0and1

这篇关于Haskell-for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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