クロージャー

クロージャーを学ぶ - 回答

目次

このページには、クロージャーを学ぶガイドの「あなたの知識をテスト」セクションの回答が含まれています。

構文

  1. REPLを使用して、7654と1234の合計を計算します。

    user=> (+ 7654 1234)
    8888
  2. 次の代数式をクロージャー式に書き直します: ( 7 + 3 * 4 + 5 ) / 10

    (/ (+ 7 (* 3 4) 5) 10)
  3. REPLドキュメント関数を使い、rem関数とmod関数のドキュメントを見ます。ドキュメントに基づいて、提供された式の結果を比較します。

    user=> (doc rem)
    clojure.core/rem
    ([num div])
      remainder of dividing numerator by denominator.
    nil
    
    user=> (doc mod)
    clojure.core/mod
    ([num div])
      Modulus of num and div. Truncates toward negative infinity.
    nil
  4. find-docを使用して、最新のREPL例外のスタックトレースを出力する関数を見つけます。

    pst

関数

  1. 引数を取らずに「Hello」を出力する関数greetを定義します。

    (defn greet []
      (println "Hello"))
  2. fn#()を使用してdefでgreetを再定義します。

    ;; using fn
    (def greet
      (fn [] (println "Hello")))
    
    ;; using #()
    (def greet
      #(println "Hello"))
  3. 関数greetingを定義します…​

    (defn greeting
      ([] (greeting "Hello" "World"))
      ([x] (greeting "Hello" x))
      ([x y] (str x ", " y "!")))
  4. 関数do-nothingを定義します…​

    (defn do-nothing [x] x)
  5. 関数always-thingを定義します…​

    (defn always-thing [& xs] 100)
  6. 関数make-thingyを定義します…​

    (defn make-thingy [x]
      (fn [& args] x))
  7. 関数triplicateを定義します…​

    (defn triplicate [f]
      (f) (f) (f))
  8. 関数oppositeを定義します…​

    (defn opposite [f]
      (fn [& args] (not (apply f args))))
  9. 関数triplicate2を定義します…​

    (defn triplicate2 [f & args]
      (triplicate (fn [] (apply f args))))
  10. java.lang.Mathクラスを使用して…​

    user=> (Math/cos Math/PI)
    -1.0
    user=> (+ (Math/pow (Math/sin 0.2) 2)
              (Math/pow (Math/cos 0.2) 2))
    1.0
  11. HTTP URLを文字列として取る関数を定義します…​

    (defn http-get [url]
      (slurp
        (.openStream
          (java.net.URL. url))))
    (defn http-get [url]
      (slurp url))
  12. 関数one-less-argを定義します。

    (defn one-less-arg [f x]
      (fn [& args] (apply f x args)))
  13. 関数two-fnsを定義します。

    (defn two-fns [f g]
      (fn [x] (f (g x))))