Clojure: idiomatic way to remove duplication in "if"?

I am very new to clojure and I haven't done a ton of lisp yet. I have a function that contains the following:

(defn chord 
    ([scale degree num_voices]
    (if 
        (keyword? degree)  
            (take num_voices (take-nth 2 (cycle (invert scale (.indexOf scale degree)))))
            (take num_voices (take-nth 2 (cycle (invert scale degree))))))

Obviously, this bad code, because the two are almost the same function call is suboptimal, where the only difference - (.indexOf scale degree)vs degree.

What is a Clojure / Lisp Method to remove this duplication of code? I feel this should include a trifle, but I'm not sure. Any other common pointers associated with this block of code are also appreciated.

Edit: I reanalyzed the code as suggested by andrew cooke, now the function reads:

(defn chord
    ([scale degree num_voices]
        (let [degree (if (keyword? degree) (.indexOf scale degree) degree)]
            (take num_voices (take-nth 2 (cycle (invert scale degree))))
        )
    )

Thanks to everyone who answered so quickly.

+5
source share
4

:

(defn chord [scale degree num_voices]
  (let [degree (if (keyword? degree) (.indexOf scale degree) degree)]
    (take num_voices (take-nth 2 (cycle (invert scale degree)))))

, - , let. , , , degree, , .

edit: , . , . YMMV.

ps [ ], ( , , ), (.. -, fn let of the form ). , , , ( , , ).

+6

if , :

(defn chord 
    ([scale degree num_voices]
    (take num_voices (take-nth 2 (cycle (invert scale (if (keyword? degree)
                                                              (.indexOf scale degree)
                                                           (invert scale degree))))))))

, , let if.

+6

Clojure ( lisps) if , . ,

(if (even? 3) 1 0)

0.

, if, :

(defn chord [scale degree num-voices]
  (take num-voices (take-nth 2
                             (cycle (invert scale 
                                            (if (keyword? degree)  
                                                (.indexOf scale degree)
                                                degree))))))

Also, in Lisp, -it is not special or reserved, so you can and should use it in your variable names. The lisp style is best used num-voicesinstead of num_voicesor numVoices, since the dotted option is considered more readable.

+4
source

There is not much to simplify the procedure, perhaps move ifinside the call to take num_voices, for example:

(defn chord ([scale degree num_voices]
   (take num_voices
         (take-nth 2
                   (cycle (invert
                           scale
                           (if (keyword? degree) (.indexOf scale degree) degree)))))))
0
source

All Articles