Question

I'm looking for a way to do while-loops or for-loops in Miranda.

I'm trying to do something like

while(blablanotfinished)
{
if(a=true)blabla
else blabla
}
Was it helpful?

Solution

Miranda doesn't have while- or for-loops (which wouldn't make much sense without mutable state anyway). In most cases you can use higher order functions instead. In cases where there is no higher-order function which does what you need, you can use recursion.

For example if you have the following while-loop in an imperative language:

f(start) {
    x = start
    while( !finished(x) ) {
        x = next(x)  
    }
    return x
}

You would express it recursively in Miranda like this:

f x = if finished x then x else f (next x)

OTHER TIPS

In Miranda (and in general, in purely functional programming languages) the use of looping constructs like WHILE, FOR, etc. is discouraged. You're expected to do iteration via recursion.

Like many other functional languages, Miranda does not have for- or while-loops. Instead, you write loops using recursion, list comprehensions or higher-order functions.

while/repeat/for-loops in functional programming style look like this:


while :: (*->bool) -> (*->*) -> * -> *
while p ff state
  = state                , if ~ (p state)
  = while p ff (ff state), otherwise

Sample: Add number to its reverse until it is a palindrome. Hints: Start value 196 leads to VERY big numbers.


isPalindrome :: num -> bool
isPalindrome n = (str = reverse str) where str = shownum n

addPalindrome :: num -> num
addPalindrome n = n + rev where rev = (numval.reverse.shownum) n

test196 :: num -> num
test196 n = while ((~).isPalindrome) addPalindrome n

test = test196 89

I hope, somebody is still interested in Gofer/Miranda/Haskell.

Annemarie Paysen (Germany)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top