2014-02-14 26 views
2

我在這裏遇到一些麻煩,希望你們可以幫忙。運營商在球拍/方案中重載

基本上,我想要做的就是重載球拍中的+符號,這樣它會添加兩個向量而不是兩個數字。另外,我想保留舊的+運營商,以便我們仍然可以使用它。我知道這應該是在計劃中工作,所以我被告知我需要使用模塊*在球拍中進行。我仍然不完全確定它是如何工作的。

這是我到目前爲止有:

#lang racket 

(module* fun scheme/base 
    (define old+ +) 
    (define + new+) 

    (define (new+ x y) 
    (cond ((and (vector? x) (vector? y)) 
      (quatplus x y)) 
      (else (old+ x y)))) 

    (define (quatplus x y) 
    (let ((z (make-vector 4))) 
     (vector-set! z 0 (old+ (vector-ref x 0) (vector-ref y 0))) 
     (vector-set! z 1 (old+ (vector-ref x 1) (vector-ref y 1))) 
     (vector-set! z 2 (old+ (vector-ref x 2) (vector-ref y 2))) 
     (vector-set! z 3 (old+ (vector-ref x 3) (vector-ref y 3))) 
     z))) 

但它似乎並沒有做任何事情。如果有人對此有所瞭解,我會非常感激。

謝謝。

+0

作爲警告,不要污衊您的問題。如果您再次這樣做,我會鎖定問題並暫停您的帳戶。 –

+1

瑕疵問題是什麼? – koziez

+0

玷污意味着大幅修改帖子以改變其含義。在這種情況下(http://stackoverflow.com/posts/21768408/revisions)OP試圖混淆整個帖子。 – GoZoner

回答

5

我會怎麼做,這是使用except-inrename-in規格爲require

#lang racket/base 

(require (except-in racket + -) 
     (rename-in racket [+ old+] [- old-])) 

(define (+ x y) 
    (cond [(and (vector? x) (vector? y)) 
     (quatplus x y)] 
     [else (old+ x y)])) 

(define (quatplus x y) 
    (vector (+ (vector-ref x 0) (vector-ref y 0)) 
      (+ (vector-ref x 1) (vector-ref y 1)) 
      (+ (vector-ref x 2) (vector-ref y 2)) 
      (+ (vector-ref x 3) (vector-ref y 3)))) 

(+ (vector 1 2 3 4) (vector 1 2 3 4)) 
;; => #(2 4 6 8) 

你也可以使用prefix-inonly-in,這將是,如果你有很多這樣的功能來命名更方便:

(require (except-in racket + -) 
     (prefix-in old (only-in racket + -))) 

的幾點:

  • 我有quatplus只是返回一個新的不可變的向量(而不是使用make-vectorset!)。它更簡單,可能更快。

  • 球拍的+接受任意數量的參數。也許你應該?

  • 正如你所寫,你的新+將失敗的非vectorvector的組合。你可能想解決這個問題:

    (+ 1 (vector 1 2 3 4)) 
    ; +: contract violation 
    ; expected: number? 
    ; given: '#(1 2 3 4) 
    ; argument position: 1st 
    ; other arguments...: 
    ; 1 
    
1

您可以使用計劃的封裝來實現您的需求爲:

(import (rename (rnrs) (+ numeric+))) 

(define + 
    (let ((vector+ (lambda (v1 v2) (vector-map numeric+ v1 v2))) 
     (list+ (lambda (l1 l2) (map  numeric+ l1 l2))) 
     ;; … 
     ) 
    (lambda (a b) 
    (cond ((and (vector? a) (vector? b)) (vector+ a b)) 
      ((and (list? a) (list? b)) (list+ a b)) 
      ;; … 
      (else (numeric+ a b)))))) 

,如果你想工作之外的任何深度,這應該工作:

(define + 
    (letrec ((vector+ (lambda (v1 v2) (vector-map any+ v1 v2))) 
      (list+ (lambda (l1 l2) (map  any+ l1 l2))) 
      (any+ (lambda (a b) 
         (cond ((and (vector? a) (vector? b)) (vector+ a b)) 
          ((and (list? a) (list? b)) (list+ a b)) 
          ;; … 
          (else (numeric+ a b)))))) 
    any+)) 

參見:

> (+ (vector (list 1 2) 3) (vector (list 11 12) 13)) 
#((12 14) 16)