Skip to content

Instantly share code, notes, and snippets.

@hsk
Last active March 4, 2023 02:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hsk/df525d136b3499055eaf8c9cc9e257c8 to your computer and use it in GitHub Desktop.
Save hsk/df525d136b3499055eaf8c9cc9e257c8 to your computer and use it in GitHub Desktop.
#lang racket
(require redex)
(define-language calc
(e ::= n (e + e) (e - e) (e * e) (e / e) (- e))
(n ::= number))
(define-metafunction calc
⊢ : e -> n
[(⊢ n) n]
[(⊢ (- e_1)) n_2
(where n_1 (⊢ e_1))
(where n_2 ,(- (term n_1)))]
[(⊢ (e_1 + e_2)) n_3
(where n_1 (⊢ e_1))
(where n_2 (⊢ e_2))
(where n_3 ,(+ (term n_1) (term n_2)))]
[(⊢ (e_1 - e_2)) n_3
(where n_1 (⊢ e_1))
(where n_2 (⊢ e_2))
(where n_3 ,(- (term n_1) (term n_2)))]
[(⊢ (e_1 * e_2)) n_3
(where n_1 (⊢ e_1))
(where n_2 (⊢ e_2))
(where n_3 ,(* (term n_1) (term n_2)))]
[(⊢ (e_1 / e_2)) n_3
(where n_1 (⊢ e_1))
(where n_2 (⊢ e_2))
(where n_3 ,(/ (term n_1) (term n_2)))]
)
(test-equal (term (⊢ ((1 + 2) + (3 + 4))))
(term 10))
(test-equal (term (⊢ ((1 + 2) * (3 + 4))))
(term 21))
(test-equal (term (⊢ (- ((1 + 2) * (3 + 4)))))
(term -21))
(test-results)
#lang racket
(require redex)
(define-language calc2
(e ::= t (e * e) (e / e))
(t ::= f (t + t) (t - t))
(f ::= n (- e) (e))
(n ::= number))
(define-metafunction calc2
⊢ : e -> n
[(⊢ n) n]
[(⊢ (- e_1)) n_2
(where n_1 (⊢ e_1))
(where n_2 ,(- (term n_1)))]
[(⊢ (e_1 + e_2)) n_3
(where n_1 (⊢ e_1))
(where n_2 (⊢ e_2))
(where n_3 ,(+ (term n_1) (term n_2)))]
[(⊢ (e_1 - e_2)) n_3
(where n_1 (⊢ e_1))
(where n_2 (⊢ e_2))
(where n_3 ,(- (term n_1) (term n_2)))]
[(⊢ (e_1 * e_2)) n_3
(where n_1 (⊢ e_1))
(where n_2 (⊢ e_2))
(where n_3 ,(* (term n_1) (term n_2)))]
[(⊢ (e_1 / e_2)) n_3
(where n_1 (⊢ e_1))
(where n_2 (⊢ e_2))
(where n_3 ,(/ (term n_1) (term n_2)))]
[(⊢ (e_1)) n_1
(where n_1 (⊢ e_1))]
)
(test-equal (term (⊢ ((1 + 2) + (3 + 4))))
(term 10))
(test-equal (term (⊢ ((1 + 2) * (3 + 4))))
(term 21))
(test-equal (term (⊢ (- ((1 + 2) * (3 + 4)))))
(term -21))
(test-equal (term (⊢ (1 + (2 - {(3 * (4 / 2))}))))
(term -3))
(test-results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment