Clojure Leiningen その4

コードの実行

  • https://codeberg.org/leiningen/leiningen/src/branch/stable/doc/TUTORIAL.md#running-code
  • REPLを実行するには lein repl を使う。
  • REPLを上記のコマンドで実行すると、プロジェクトのコンテキストと共にコードを実行する対話型プロンプトが起動する。
  • :dependencies に記載したライブラリや、プロジェクトのコードを呼び出し動作を確認することができる。
  • 実行例。
vagrant@ubuntu2204:~/source/temp$ lein repl
nREPL server started on port 46115 on host 127.0.0.1 - nrepl://127.0.0.1:46115
REPL-y 0.5.1, nREPL 0.9.0
Clojure 1.11.1
OpenJDK 64-Bit Server VM 17.0.5+8-LTS
    Docs: (doc function-name-here)
          (find-doc "part-of-name-here")
  Source: (source function-name-here)
 Javadoc: (javadoc java-object-or-class-here)
    Exit: Control+D or (exit) or (quit)
 Results: Stored in vars *1, *2, *3, an exception in *e

temp.core=> (foo "bookstore")
bookstore Hello, World!
nil
temp.core=> (require '[clj-http.client :as http])
nil
temp.core=> (def response (http/get "https://leiningen.org"))
#'temp.core/response
temp.core=> (keys response)
(:cached :request-time :repeatable? :protocol-version :streaming? :http-client :chunked? :reason-phrase :headers :orig-content-encoding :status :length :body :trace-redirects)
temp.core=> (:status response)
200
temp.core=> (:headers response)
{"Server" "Apache", "Upgrade" "h2", "Content-Type" "text/html", "Content-Length" "2506", "Permissions-Policy" "interest-cohort=()", "Strict-Transport-Security" "max-age=31536000", "Connection" "Upgrade, close", "Accept-Ranges" "bytes", "Expires" "Sun, 13 Nov 2022 11:29:52 GMT", "ETag" "\"1e19-5e5e706584773-gzip\"", "Date" "Sun, 13 Nov 2022 11:19:52 GMT", "Vary" "Accept-Encoding,User-Agent", "Last-Modified" "Wed, 10 Aug 2022 18:14:50 GMT", "Cache-Control" "max-age=600"}
  • REPLではなく、エントリポイントを直接実行する場合は lein run コマンドを使う。
  • lein run コマンドを使う場合には project.clj の :main-main 関数が定義されている名前空間を指定する。
  • 例えばこう。
(defproject temp "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
            :url "https://www.eclipse.org/legal/epl-2.0/"}
  :main temp.core
  :dependencies [[org.clojure/clojure "1.11.1"]
                 [clj-http "3.12.3"]]
  :repl-options {:init-ns temp.core})
  • temp.core名前空間のコードはこうなっている。
(ns temp.core)

(defn foo
  "I don't do a whole lot."
  [x]
  (println x "Hello, World!"))

(defn -main "Application entry point" [] (foo "bookstore"))
  • 実行してみる。
vagrant@ubuntu2204:~/source/temp$ lein run
bookstore Hello, World!