Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - for loop

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;

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

like image 755
Joe Avatar asked Aug 24 '16 19:08

Joe


People also ask

Is there a for loop in Haskell?

Recursion is important to Haskell because unlike imperative languages, you do computations in Haskell by declaring what something is instead of declaring how you get it. That's why there are no while loops or for loops in Haskell and instead we many times have to use recursion to declare what something is.

Does Haskell have iteration?

Haskell : iterate. Description: creates an infinite list where the first item is calculated by applying the function on the secod argument, the second item by applying the function on the previous result and so on.

Is for loop iterative?

A Survey of Definite Iteration in Programming. Definite iteration loops are frequently referred to as for loops because for is the keyword that is used to introduce them in nearly all programming languages, including Python. Historically, programming languages have offered a few assorted flavors of for loop.


2 Answers

There are a few options. First, you can rewrite the problem with naive recursion:

loop :: Int -> Int
loop n = loop' n 0
  where loop' 0 a = a
        loop' n a = loop' (n - 1) (1 - a)

Next, you can restate recursion as a fold:

loop :: Int -> Int
loop n = foldr (\a _ -> 1 - a) 0 [0..n]

Or you can use State to simulate a for loop:

import Control.Monad
import Control.Monad.State

loop :: Int -> Int
loop n = execState (forM_ [0..n] 
                      (\_ -> modify (\a -> 1 - a))) 0
like image 79
user2297560 Avatar answered Sep 21 '22 10:09

user2297560


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
like image 28
Code-Apprentice Avatar answered Sep 22 '22 10:09

Code-Apprentice