5

I want to be able to do this. For example, this is my code:

    (cond [true AA]
          [else BB])

In AA, I want it to do 2 things. 1 is to set the value of a global variable, and then return a string. How would I go about doing that?

Óscar López
  • 232,561
  • 37
  • 312
  • 386
nonion
  • 826
  • 2
  • 9
  • 18
  • 1
    I think 90% of the time you need to use `begin`, it's with `if` (another 5% would be when writing macros). Plus, Racket favors `cond` (or `match`) over `if`, so if you follow that you'll rarely use `begin`. It's good to understand `begin`, but it's one of those things you'll learn early on that you'll use surprisingly little in most practical code. (Much like you learn to write loops as recursive functions, and it's important to learn that, and sometimes you'll truly _need_ that, but mostly you'll actually use things like `map` or `for/list`.) – Greg Hendershott Jun 11 '13 at 14:41

3 Answers3

9

In the cond special form, there's an implicit begin after each condition, so it's ok to write several expressions, remembering that only the value of the last one will be returned. Like this:

(cond [<first condition>
       (set! global-variable value)
       "string to return"]
      [else
       "other return value"])
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

This sort of thing can be easily found in the Scheme R5RS specification. It really is worth a read as it is one of the finest language specifications ever written!

Other syntactic keywords that you might find of use:

(if <predicate> <consequent> <alternate>)
(begin <expression-or-declaration> ... <expression>)
(case <expression> <case-clause> ...)
(and <test> ...)
... others ...
GoZoner
  • 67,920
  • 20
  • 95
  • 145
0

create a helper function that does 2 things. have your if statement call said function when appropriate:

(cond [(test? something) (your-function your-data)]
      [else (another-function your-data)])

A less straightforward way would be to call two functions and "link" them with an "and":

(cond [(test? something) 
        (and (do-this data) (do-that data))]
      [else (do-something-else data)])
mikesi2
  • 41
  • 3