I don't know if this is the right place for a post about Scheme, but i was wondering if anyone knew if there are loops and if statements in Scheme? (I am very new to Scheme, i know there are 'cond' statements, but i don't know if there are if's, or if there's a difference between the two)

if there are in fact loops, an example of the syntax would be greatly appreciated.


Scheme does have an if expression. It's used as (if condition then-expression else-expression) and works in the obvious way (i.e. it evaluates then-expression if the condition is true and else-expression if its not - the result of evaluating an if expression is the result of whichever of then-expression or else-expression was evaluated).

The difference between cond and if is that cond can take an arbitrary number of conditions and associated expressions, while if takes only one condition. cond also allows you to specify more than one expression for a given condition (which will be evaluated in order) - if you wanted to evaluate more than one expression with if, you'd need to use begin inside the if. So cond is basically a more versatile form of if.

The ways to do loops in Scheme are:

  1. Recursive functions┬╣
  2. The do form, which lets you specify a list of variables, that each have a starting value and an expression to calculate its new value, and a body. At the beginning of the loop each variable will be set to its starting value. While the condition evaluates to true, the body will be evaluated and after each iteration each variable will be set to the result of evaluating its respective expression. So basically it's a while-loop that allows you to specify how variables are updated declaritively.
  3. The named let construct, which basically works like defining a local recursive function and immediately calling it.

For more information see the Scheme standard's section on iteration constructs.

┬╣ The Scheme standard mandates that a Scheme implementation must optimize tail recursion, so tail-recursive functions are an efficient way to implement loops in Schme.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.