2017-07-20 1 views
6

私はラケットで働いていますが、私の知る限りでは、これは一般的にスキームにおける場合です。あなたが持っている場合Scheme/Racketの条件に基づいて実際に多くのことを定義する方法はありますか?

(define x 
    (if condition 
     "do a backflip" 
     "do a barrel roll")) 

しかし:私は、代わりにこのような何かを行うことができ、この特定のケースのための今すぐ

(if condition 
    (define x "do a backflip") 
    (define x "do a barrel roll")) 

:あなたは私たちが表現コンテキストで何かを定義しようとしているため、このような何かを行うことはできません代わりの

(if condition 
    (begin (define x "do a backflip") 
      (define y "awesome") 
      (define z "shoot me")) 
    (begin (define x "do a barrel roll") 
      (define y "nice") 
      (define z "give me sweet release"))) 

たちは

を取得しているため、これを定義するためのさまざまな事柄の多くは、本当にひどい取得しますそれができるようDRYではありません
(define x                                                          
    (if condition 
     "do a backflip" 
     "do a barrel roll")) 
(define y                                                          
    (if condition 
     "awesome" 
     "nice")) 
(define z                                                          
    (if condition 
     "shoot me" 
     "give me sweet release")) 

、我々は常にconditionのためにテストを繰り返しています。そして、その結果は、我々がother-conditionをチェックしたい場合は代わりに、テストのconditionのために、私たちは物事の量が定義されているnのために変更n回をしなければならないということです。これを行うためのよりよい方法がありますか?その場合:どのように?

答えて

5

使用define-values: "ロット" は本当に大きい場合

(define-values (x y z) (if condition 
          (values "do a backflip" "awesome" "shoot me") 
          (values "do a barrel roll" "nice" "give me sweet release"))) 
4

することは、あなたはラケットのunitsを使用する場合があります。

(define-unit [email protected] 
    (import) (export acro^) 
    (define x "do a backflip") 
    (define y "awesome") 
    (define z "shoot me")) 

(define-unit [email protected] 
    (import) (export acro^) 
    (define x "do a barrel roll") 
    (define y "nice") 
    (define z "give me sweet release")) 

あなたが動的に選択することができます。そして、定義の異なるセットを含む単位を定義

(define-signature acro^ (x y z)) 

を:

まず定義したいすべての変数と署名を定義しますどのユニットを起動して、署名内の名前にバインドします:

`定義-values`の上にこの利点は何でしょう
(define-values/invoke-unit 
    (if .... [email protected] [email protected]) 
    (import) (export acro^)) 

x 
;; => either "do a backflip" or "do a barrel roll", depending on condition 
+0

? – Wysaard

関連する問題