3

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
}
hammar
  • 138,522
  • 17
  • 304
  • 385
user23012
  • 219
  • 2
  • 16

4 Answers4

3

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)
sepp2k
  • 363,768
  • 54
  • 674
  • 675
1

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)

Max Krizh
  • 585
  • 3
  • 7
  • 34
1

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

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.

hammar
  • 138,522
  • 17
  • 304
  • 385