Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #lang racket
- #;(define (boucle-musik x)
- (let*((n 0))
- (letrec ((loop (lambda ()
- (cond((> n 5)
- (begin
- (set! n 1)
- (play (list-ref play-liste1 n))
- (loop)))
- ((begin
- (set! n (+ n 1))
- (play (list-ref play-liste1 n))
- (loop))))))))))
- ; "Why doesn't this work?
- ; Hi C.C.:
- ; a couple of syntax errors.
- ; First I'll re-do your code but use some different parens.
- ; (Note that racket views all parens as identical, so long as they match -- e.g. `[+ 2 {* 3 4}]`
- ;
- #;(define (boucle-musik x)
- (let* {[n 0]}
- (letrec {[loop (lambda ()
- (cond[(> n 5) ; first cond-question
- (begin ; first cond-answer
- (set! n 1)
- (play (list-ref play-liste1 n))
- (loop))]
- [ ; second cond-question missing!
- (begin ; second cond-answer
- (set! n (+ n 1))
- (play (list-ref play-liste1 n))
- (loop))]))
- ] ; end the binding for `loop`
- } ; only one letrec binding
- ; No body for 'letrec' here
- )))
- ; So the first syntax error, as DrRacket reports, is that 'letrec' has no body.
- ; Presumably you meant to call `(loop)` there
- ; Second syntax error is that the second cond-question is missing.
- ; You could use `else`.
- ; Third, there's an idiomatic preference to avoid mutation.
- ; If you want to have n start as 0, and increment on each call to `loop`,
- ; just make it a parameter to `loop`.
- ; Putting those together, I get:
- (define (boucle-musik-v2 play-liste1) ;<-- I presume the play-list should be passed in
- (letrec {[loop (lambda (n)
- (cond[(> n 5) ; first cond-question
- (begin ; first cond-answer
- (play (list-ref play-liste1 n))
- (loop 1))]
- [ ; second cond-question missing!
- (begin ; second cond-answer
- (play (list-ref play-liste1 n))
- (loop (+ n 1)))]))
- ] ; end the binding for `loop`
- } ; only one letrec binding
- (loop 0) ; the letrec body
- ))
- ; Finally, we can factor out the calls to `play`,
- ; and take advantage that lambda-bodies have an implicit `begin` in racket:
- ;
- (define (boucle-musik-v3 play-liste1)
- (letrec {[loop (lambda (n)
- (play (list-ref play-liste1 n))
- (loop (cond [(> n 5) 1]
- [else (+ 1 n)])))]}
- (loop 0) ; the letrec body
- ))
- ; and post-finally, some cool new syntax:
- ; "named let" is a way to make a function whose parameters are
- ; the variables-you're-declaring.
- ; So I'd write the above as:
- ;
- (define (boucle-musik-v4 play-liste1)
- (let my-play-loop {[n 0]}
- (play (list-ref play-liste1 n))
- (my-play-loop (if (> n 5) 1 (+ 1 n)))))
- (define play-list1 '(a b c d e f g))
- (define (play sng) (printf "playing ~v~n" sng))
- (boucle-musik-v4 '(a b c d e f g))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement