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?)
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With