clojureでgraphic programming

Clojureとは

Clojureは2008年にできたJava Virtual Machine上で動く言語です。

関数プログラムでLispと構文を継承しつつあり、関数プログラムは教養として1つぐらい学んでいたほうがいいので、ちょこちょこ触ることにしました。

関数プログラムを学びにあたり、Lispあたりか入ろうと思ったのですが、Herokuに対応しているし、Creative Applicationで紹介されたということでClojureを勉強することにしました。

関数プログラムはすごい、柔軟だという話をちょこちょこ聞き、なにがすごいのかわからず、Clojureの勉強を通して、探っていければと思っています。


ClojureをMac上で動かすまで、、

Creative ApplicationのTutorialがとても役に立ちました。

http://www.creativeapplications.net/tutorials/introduction-to-clojure-part-1/

LeiningenというPacage Managementをインストールするだけで動くようになります。

Leiningen: http://leiningen.org/

Install後、Terminal上でlein replと入力すれば、動きます。


Quilって!?

QuilというPackageでProcessingのように簡単にビジュアルコーディングがClojureできるそうです。

https://github.com/quil/quil

QuilのディレクトリからLein installでQuil Paackgeでインストール。


Sampleを動かすまで、、、

clojure appを生成します。

	lein new app my-cpp

appを管理するproject.cljというファイルのdependenciesに[quil “1.7.0”]を追加する。

実行ファイルは/src/my_stuff/core.cljというファイルになります。

Quilのページにあるサンプルを動かしてます。

(ns my-stuff.core
  (:require [quil.core :refer :all]))

(defn setup []
  (smooth)                          ;; Turn on anti-aliasing
  (frame-rate 1)                    ;; Set framerate to 1 FPS
  (background 200))                 ;; Set the background colour to
                                    ;; a nice shade of grey.
(defn draw []
  (stroke (random 255))             ;; Set the stroke colour to a random grey
  (stroke-weight (random 10))       ;; Set the stroke thickness randomly
  (fill (random 255))               ;; Set the fill colour to a random grey

  (let [diam (random 100)           ;; Set the diameter to a value between 0 and 100
        x    (random (width))       ;; Set the x coord randomly within the sketch
        y    (random (height))]     ;; Set the y coord randomly within the sketch
    (ellipse x y diam diam)))       ;; Draw a circle at x y with the correct diameter

(defsketch example                  ;; Define a new sketch named example
  :title "Oh so many grey circles"  ;; Set the title of the sketch
  :setup setup                      ;; Specify the setup fn
  :draw draw                        ;; Specify the draw fn
  :size [323 200])    	

core.cljの以上のようなコードを書いて、保存します。

保存後、appのトップディレクトリでlein runと書き、実行する。ウィンドゥが現れます。Sampleは動きます。


今後に向けて

clojureの文法に慣れるために、Quilで遊んでみつつ、OpenGLが動かすぐらいになりたいと思います。

Leave a comment