gpt4 book ai didi

racket - 使用带有自定义结构的内置数学运算符

转载 作者:行者123 更新时间:2023-12-04 18:18:48 25 4
gpt4 key购买 nike

我希望能够做这样的事情:

(struct point (x y))

(define p1 (point 1 2))
(define p2 (point 10 20))

(+ p1 p2) ; -> (point 11 22)

是否可以教授像 point 这样的结构?使用内置数学运算符,如 + ?

文档似乎设法实现自定义 (equal? ...)this page 上的第 5.5 节中处理.我正在尝试做的非常相似......

或者我应该定义像 (point-add p1 p2) 这样的函数?

最佳答案

你可以

  • 一起去 point-add
  • 使用您自己的 +与您想要采用的所有可能的值类型相匹配。如果您事先知道所有可能的值类型,这就足够了,但是扩展它以在客户端代码中包含新创建的结构定义并不容易。例如:
    ;; We will "shadow" Racket's + with our own +, but we still
    ;; need the functionality of Racket's +, so let's require
    ;; Racket's + but use the name racket:+ instead
    (require (only-in racket/base [+ racket:+]))

    (struct point (x y) #:transparent)

    (define (+ x y)
    (match* (x y)
    [((point a b) (point c d)) (point (+ a c) (+ b d))]
    [((point _ _) _) (error '+ "Can't add a point with non point")]
    [(_ (point _ _)) (error '+ "Can't add a point with non point")]
    [(_ _) (racket:+ x y)]))

    ;; in client's code

    (+ (point 1 2) (point 3 4)) ;=> (point 4 6)
    (+ 1 2) ;=> 3
  • 定义一个新的 generics这样我们就可以做类似 gen:equal+hash 的事情为 equal? .例如:
    (require racket/generic
    (only-in racket/base [+ racket:+]))

    (define-generics addable
    (add addable _)
    #:fast-defaults ([number?
    (define (add x y) (racket:+ x y))]))

    (define + add)

    ;; in client's code

    (struct point (x y)
    #:transparent
    #:methods gen:addable
    [(define (add x y)
    (match* (x y)
    [((point a b) (point c d)) (point (+ a c) (+ b d))]
    [(_ _) (error 'add "Can't add a point with non point")]))])

    (struct point-3d (x y z)
    #:transparent
    #:methods gen:addable
    [(define (add x y)
    (match* (x y)
    [((point-3d a b c) (point-3d d e f))
    (point-3d (+ a d) (+ b e) (+ c f))]
    [(_ _) (error '+ "Can't add a point-3d with non point-3d")]))])

    (+ (point 1 2) (point 3 4)) ;=> (point 4 6)
    (+ (point-3d 1 2 3) (point-3d 4 5 6)) ;=> (point-3d 5 7 9)
    (+ 1 2) ;=> 3
  • 要接受多个参数,将(3)修改如下
    (define +
    (case-lambda
    [() 0]
    [(x . xs) (foldl add x xs)]))

    ;; client's code

    (+ (point 1 2) (point 3 4) (point 5 6)) ;=> (point 9 12)
    (+ 1 2 3) ;=> 6
    (+) ;=> 0
    (+ 1) ;=> 1
    (+ (point-3d 1 2 3)) ;=> (point-3d 1 2 3)
  • 关于racket - 使用带有自定义结构的内置数学运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55876455/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com