【心得】
defn
裡面還有包 def
的寫法,知道有 let
的寫法,但在只需要一個變數情況下,看起來比較簡潔!補充:昨天提到怎麼 clojure 沒有 sum
function,問了大大才意識到,其實 +
就做到了呀!在 ruby 或大多的語言 +
是 operator(ruby 是有 + 的 method 沒錯),位置放在 suffix ex. 1 + 1,所以只能接收兩個 argument。但 clojure 世界把它當成 function 且又是 prefix,就做到了能接收無限多個 argument,這不就是 sum 效果嗎!ex. (+ 1 2 3 4)
【今日湯底】
After a hard quarter in the office you decide to get some rest on a vacation. So you will book a flight for you and your girlfriend and try to leave all the mess behind you.
You will need a rental car in order for you to get around in your vacation. The manager of the car rental makes you some good offers.
Every day you rent the car costs $40. If you rent the car for 7 or more days, you get $50 off your total. Alternatively, if you rent the car for 3 or more days, you get $20 off your total.
Write a code that gives out the total amount for different days(d).
(必須通過以下測試)
(ns rentalcarcost.core-test
(:require [clojure.test :refer :all]
[rentalcarcost.core :refer :all]))
(defn test-assert [act exp]
(is (= act exp)))
(deftest a-test1
(testing "rental-car-cost"
(test-assert (rental-car-cost 1) 40)
(test-assert (rental-car-cost 3) 100)
(test-assert (rental-car-cost 8) 270)
))
【我的答案】
(ns rentalcarcost.core)
(defn rental-car-cost [d]
(cond
(and (>= d 0) (< d 3)) (* 40 d)
(and (>= d 3) (< d 7)) (- (* 40 d) 20)
(>= d 7) (- (* 40 d) 50)
)
)
思路:
【其他人的答案】
(ns rentalcarcost.core)
(defn rental-car-cost [d]
(let [init (* d 40)]
(cond
(>= d 7) (- init 50)
(>= d 3) (- init 20)
:else init)))
(ns rentalcarcost.core)
(defn rental-car-cost [d]
(def cost (* d 40) )
(cond
(>= d 7) (- cost 50)
(>= d 3) (- cost 20)
:else cost
)
)