Schematic: difference between define and define-syntax-rule

I was given two if-statements in Racket:

(define (if-fun c thn els) (if c thn els))
(define-syntax-rule (if-mac c thn els) (if c thn els))

Can someone think about explaining the differences between how these two if statements are evaluated and provide an example using each if-statement definition? I find it difficult to distinguish how macros and function arguments are evaluated in this example. I tried small examples, for example:

(if-fun (> 3 4) true false)  ;; #f
(if-mac (> 3 4) true false)  ;; #f

But it is clear that this does not help me differentiate the two definitions.

-Thanks

+4
source share
2 answers

From your comment, it sounds like you already understood it. The main question is: when (ever) are assessments made?

, , .

  • : (thing other stuff). , thing . . .

  • , define-syntax-rule , define . . , , , , . !


  • , , . if-fun (/ 1 0) . ( ), if-fun.

    (Sidenote: "thunks", . if-lazy thn els, /when needed. , els.)

  • :

    • : . , .

    • : . . , . , if-mac . if, ( ), , .


, , then else - , .

+5
(define (verbose arg)
  (display arg) ; display 
  (newline)     ; display newline
  arg))         ; evaluate to arg

(if-fun (verbose (> 3 4)) 
        (verbose 'true) 
        (verbose 'false))
; ==>  false

#f
true
false

:

(if-mac (verbose (> 3 4)) 
        (verbose 'true) 
        (verbose 'false))
; ==>  false

#f
false

? , .

, . , , #f.

:

(define (factorial n)
  (if-fun (<= n 2)
          n
          (* n (factorial (- n 1)))))

(factorial 2)

, , ( 1), ( 0), ( -1)..... . , , .

(define (factorial n)
  (if-mac (<= n 2)
          n
          (* n (factorial (- n 1)))))

(factorial 2)

, , :

(define (factorial n)
  (if (<= n 2)
      n
      (* n (factorial (- n 1)))))

, . , - , , , .

, Scheme Racket . . #!lazy racket, #!racket, if, , . .

0

Source: https://habr.com/ru/post/1611461/


All Articles