1,105,633 Community Members

Scheme loops?

Member Avatar
doomsday1216
Newbie Poster
13 posts since Sep 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

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.

Thanks.

Member Avatar
sepp2k
Posting Pro in Training
458 posts since Jul 2012
Reputation Points: 300 [?]
Q&As Helped to Solve: 96 [?]
Skill Endorsements: 23 [?]
 
0
 

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.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: