We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,642 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Scheme loops?

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.

2
Contributors
1
Reply
7 Months
Discussion Span
10 Months Ago
Last Updated
4
Views
doomsday1216
Newbie Poster
13 posts since Sep 2011
Reputation Points: 10
Solved Threads: 2
Skill Endorsements: 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.

sepp2k
Posting Whiz in Training
244 posts since Jul 2012
Reputation Points: 76
Solved Threads: 45
Skill Endorsements: 8

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 0.0522 seconds using 2.66MB