Showing posts with label clojure. Show all posts
Showing posts with label clojure. Show all posts

Wednesday, October 27, 2010

ติดใจ repl ของ Clojure

ช่วงนี้ research หาลู่ทางรับงานจากอเมริกา
โจทย์ก็คือไป crawl ดึงข้อมูล จาก medicare.gov
ความยากอยู่ตรง site นั้นใช้ .net เขียนแบบ component based (stateful)
การจะได้ข้อมูลมา ต้องฝ่าด่านตอบคำถาม จำนวน 4-5 หน้าเข้าไปก่อน
ก็เลยต้องใช้ browser จริงๆเข้าไปดึงข้อมูล

หวยก็เลยออกมาที่ Selenium + WebDriver
แต่ครั้นจะเขียนด้วย java ก็ไม่สนุก
เขียนด้วย ruby/python ก็เคยเขียนแล้ว
ก็เลยเลือกใช้ Clojure

Lisp มันมีข้อดีอย่างหนึ่งก็คือ
มันมี REPL ทำให้เราสามารถเขียนโปรแกรมในลักษณะ incremental ได้
เขียนไป ทดลองไป ปรับแต่งไป

สภาพแวดล้อมที่เลือกใช้พัฒนาก็คือ
emacs + cake

ลองดูตัวอย่าง ตอนทดสอบได้ใน video นี้
(ดูช่วงต้นๆก็พอ, net/web มันช้า หลังๆหมดไปกับการรอมันโหลด
ใครว่า web ราชการไทยช้า web ราชการฝรั่งก็ช้าเหมือนกัน)



Updated: video upload ผ่านทาง blogger ได้ความละเอียดต่ำเหลือเกิน
ดูรูปประกอบแล้วกัน



ตัวอย่าง code ที่ใช้

(defn send-key [by txt]
(let [elm (.findElement *driver* by)]
(.sendKeys elm (into-array [txt]))))

(defn click [by]
(let [elm (.findElement *driver* by)]
(.click elm)))

(defn init-queue []
(def *queue* (LinkedBlockingQueue.)))

(defn start-thread [driver func]
(.start
(Thread.
(fn []
(loop []
(let [code (.take *queue*)]
(binding [*driver* driver]
(func code)))
(recur))))))

(defn fetch [code]
(go "https://www.medicare.gov/find-a-plan/questions/home.aspx")
(send-key (by-css-selector "div#zip-code-field > input") code)
(click (by-css-selector "input[type=submit][alternatetext=\"Find Plans\"]")))

Related link from Roti

Tuesday, December 02, 2008

เรียนรู้ Clojure ตอน tail recusive

recursive คือหัวใจหลักของภาษาตระกูล functional, ตัว runtime ของภาษาตระกูลนี้ต้องออกแบบมาให้สามารถทำ optimize tail recursive เพื่อหลีกเลี่ยง stack overflow. โชคร้ายที่ jvm ไม่ได้ออกแบบมาเพื่อทำ optimize แบบนั้น (ยกเว้น IBM JVM - Java กับ Tail-Recursive)
เจ้า closure ก็เลยต้องอาศัย syntax พิเศษเพื่อเลียนการทำงานแบบ tail recursive

ลองดูตัวอย่าง code จริง
(defn render-level-layer
"my, what an insane level representation i have here"
[target items if-empty if-full]
(loop [target target
remain (seq items)]
(if remain
(let [x (:x (first remain))
y (:y (first remain))
i (level-index x y)
at (target i)]
(recur (assoc target i (if (= at \space) if-empty if-full))
(rest remain)))
target)))

keyword จะอยู่ที่ loop กับ recur นี่แหล่ะ
loop เป็น syntax แบบเดียวกับ let แต่มันจะกำหนดจุดที่จะเกิดการ recursion
ส่วน recur เป็นการสั่งให้กระโดดกลับไปทำงานที่ loop อีกครั้ง แต่จะมีการเปลี่ยน binding ของตัวแปรที่กำหนดไว้ตอนประกาศ loop

ลองดูตัวอย่างข้างล่าง ซึ่งเป็นการหาค่า factorial โดยใช้วิธี recursive แบบ pass ค่า accumulator
จะเห็นว่าที่ตำแหน่ง loop มีการกำหนด binding ตัวแปร cnt กับ acc
ดังนั้นเมื่อถึงตอนสั่ง recur ก็จะต้องส่ง parameter ที่จะเป็นค่าใหม่ของ cnt และ acc กลับมาด้วย
(def factorial
(fn [n]
(loop [cnt n
acc 1]
(if (zero? cnt)
acc
(recur (dec cnt) (* acc cnt))))))

เปรียบเทียบกับการเขียนแบบ recursive ใน clisp ก็จะเป็นแบบนี้
(defun factorial (n &optional (acc 1))
(if (<= n 1)
acc
(factorial (- n 1) (* acc n))))


หลังจากที่ Clojure ออกมา ก็มีคนถามประเด็น mutual recursive ว่าจะเขียนอย่างไร
ลองดูตัวอย่าง mutual recursive ก่อน
(declare bar) 

(defn foo [n]
(if (pos? n)
(bar (dec n))
:done-foo))

(defn bar [n]
(if (pos? n)
(foo (dec n))
:done-bar))

(foo 1000000)
-> java.lang.StackOverflowError

Note: code แบบข้างบนนี้ ถ้าไปเขียนใน clisp จะ run ได้โดย stack ไม่ overflow

Rich Hickey ก็เลยแก้ code ของ clojure โดยใช้ technique ที่เรียกว่า trampoline
instead of actually making a call in the tail, a function returns the function to be called, and a controlling loop calls it


syntax ของ foo bar ข้างบนก็เลยต้องเขียนแบบนี้แทน
(declare bar) 

(defn foo [n]
(if (pos? n)
#(bar (dec n))
:done-foo))

(defn bar [n]
(if (pos? n)
#(foo (dec n))
:done-bar))

Related link from Roti

Monday, November 24, 2008

เรียนรู้ Clojure ตอนที่ 3

Clojure ประกาศตัวชัดเจนว่า มันไม่ได้เป็น OOP (ถึงแม้จะ run อยู่บน platform ที่เป็น OOP จ๋าแบบ Java)
และเลือกข้าง functional อย่างชัดเจน (ไม่เหมือน scala ที่เลือกมันสองข้างเลย)

มาลองดู code ที่ตัดมาจากตัวอย่าง code ในตอนที่ 1
(ns test
(:import (java.util.regex Pattern)))

(defstruct pos :x :y)

(defn explode
"return a pos/type seq for each char in the line"
[y line]
(map (fn [x y type] (vector (struct pos x y) type))
(iterate inc 0) (repeat y) line))

(defn line-explode
"call explode on each line with the appropriate y"
[lines]
(let [linesplit (. Pattern compile "\n" (. Pattern MULTILINE))] ; must be a better way?
(reduce into
(map explode
(iterate inc 0)
(. linesplit split lines)))))


เริ่มด้วยบรรทัดบนสุด เป็นการระบุ namespace (ถ้าเทียบกับ java ก็คือ package)
(ns test
(:import (java.util.regex Pattern)))

บรรทัดที่สองบอกด้วยว่าให้ import class java.util.regex.Pattern เข้ามาด้วย
(note: ใน clojure มันมี syntax สำหรับ regex ให้ใช้เหมือนกัน แต่คนเขียนเลือกใช้แบบเรียกผ่าน java)

มาดู function line-explode ก่อน
จะเห็นเขาประกาศ function ด้วย form แบบนี้
(defn function-name description params body)

เข่น

(defn plus-9 "plus with 9" [x] (+ x 9))

โปรแกรมตระกูล lisp นี่, ตัว code ก็เป็น data structure ด้วย
ดังนั้นจะเห็นว่า params ก็คือ vector type, ส่วน body เป็น list type

จาก code จะเห็นว่า function explode รับ parameter ตัวเดียว ก็คือ lines
(defn line-explode
"call explode on each line with the appropriate y"
[lines]

ตัว body ของ function line-explode จะอยู่ในรูป let syntax
(let bindings body)
เช่น
(let [x 9, y 10] (+ x y))

run แล้วได้ผลลัพท์เป็น 19

ใน bindings ของ let นั้น, variable ที่ถูก bind ก่อน สามารถถูกอ้างถึงโดย variable ที่ bind ทีหลังได้

(let [x 9, y (+ x 7)] (+ x y))

run แล้วได้ผลลัพท์เป็น 25

ลองดู bindings ของโปรแกรมตัวอย่าง
(let [linesplit (. Pattern compile "\n" (. Pattern MULTILINE))] ; must be a better way?

ถ้าเทียบกับ java แล้วบรรทัดข้างบนก็คือ
Pattern linesplit = Pattern.compie("\n", Pattern.MULTILINE);


ที่นี้ก็มาถึง body ของ function line-explode
    (reduce into
(map explode
(iterate inc 0)
(. linesplit split lines)))

เวลาอ่านก็ให้ไล่จากในออกมาข้างนอก
เริ่มจากในสุด
(. linesplit split lines)
ก็คือการเรียกใช้ method split บน Pattern instance (ในที่นี้ก็คือการตัดที่ตำแหน่ง new-line)

(iterate inc 0)
ตรงนี้เขา show ความสามารถของ infinite-sequence และ lazy behavior ของ Clojure
โดยผลลัพท์ที่ได้จะ เป็นไปตามกฎนี้
สมาชิกตัวแรกของผลลัพท์เกิดจากการเรียกใช้ (inc 0) ซึ่งจะได้ผลลัพท์เป็น 1
ผลลัพท์ตัวที่สองเกิดจากการเรียกใช้ (inc ผลลัพท์ตัวแรก) ซึ่งก็คือ (inc 1)
ผลลัพท์ตัวถัดๆไปก็คือ (inc ผลลัพท์ตัวก่อนหน้ามัน)
ดังนั้น (iterate inc 0) จะได้ผลลัพท์เป็น (1 2 3 4 5 6 ... infinity)

ส่วน function map นี้ เดี๋ยวนี้นิยมใช้กันมากแล้ว คงไม่ต้องอธิบาย
แต่ว่า map ของพวก lisp นี้เขารับ collection ได้หลาย collection พร้อมๆกัน
ลองดูตัวอย่างนี้

(map + '(1 2 3) '(3 4 5))
=> (4 6 8)
(map + '(1 2 3) '(3 4 5 6 7 8))
=> (4 6 8)

เนื่องจากเจ้า map function มันไปเรียกใช้ function explode ดังนั้นเราต้องตามไปดูว่ามันทำอะไร

(defn explode
"return a pos/type seq for each char in the line"
[y line]
(map (fn [x y type] (vector (struct pos x y) type))
(iterate inc 0) (repeat y) line))

ใน code ข้างบนจะเห็นว่ามี fn ในบรรทัดที่ 4 โดยมันคือการ define function อีกแบบหนึ่ง ซึ่งมีคุณสมบัติแบบ closure
นั่นคือมันจะจับ ตัวแปร ณ scope ที่มันถูกประกาศ

test> (def foo
(let [y 10]
(fn [x] (+ x y))))
#=(var test/foo)
test> (foo 7)
17

ลองเปลี่ยน y ให้เป็น 12 ณ ขณะที่ run
test> (let [y 12] (foo 7))
17

ตัว repeat นั่นเป็น infinite list อีกตัวหนึ่ง
(repeat 7)
=> (7 7 7 7 7 7 7 7 7 .....)

ดูจาก code แล้วจะเห็นว่า function explode มันก็คือการสร้าง list ของ (pos x y) char นั่นเอง
ทดลอง run ดู
test> (explode 0 "hello")
([{:x 0, :y 0} \h] [{:x 1, :y 0} \e] [{:x 2, :y 0} \l] [{:x 3, :y 0} \l] [{:x 4, :y 0} \o])

กลับมาที่ line-explode, function ตัวสุดท้ายก็คือ (reduce into (map ..))
reduce รับ parameter เป็น function และ list
โดยมันจะเรียก function โดยมี parameter เป็นสมาชิกตัวที่ 1 และ 2 ของ list
จากนั้นก็จะเรียก function โดยมี parameter ตัวที่เป็นผลลัพท์ที่ได้จากครั้งก่อน กับ สมาชิกตัวที่ 3
ทำเช่นนี้ไปเรื่อยๆจนกว่าจะหมด
(reduce + [1 2 3 4 5])
=> 15
เขียนอีกอย่างก็คือ
(+ (+ (+ (+ 1 2) 3) 4) 5)

ส่วน into นั้นทำงานแบบนี้
(into [1] [2])
=> [1 2]
(into [1 2 3] [2])
=> [1 2 3 2]
(into [1] [1 2 3])
=>[1 1 2 3]

มันคือ operation ที่จับ array บวกกันนั่นเอง

สรุปแล้วจะเห็นว่าการ explode ก็คือการเปลี่ยน multi-line string ให้อยู่ในรูปของ [(pos x y) char] นั่นเอง

test> (line-explode "hello\nworld\n")
([{:x 4, :y 1} \d] [{:x 3, :y 1} \l] [{:x 2, :y 1} \r] [{:x 1, :y 1} \o] [{:x 0, :y 1} \w] [{:x 0, :y 0} \h] [{:x 1, :y 0} \e] [{:x 2, :y 0} \l] [{:x 3, :y 0} \l] [{:x 4, :y 0} \o])

Related link from Roti

Friday, November 21, 2008

เรียนรู้ clojure - data structure ตอน 2

ต่อจากเมื่อวาน
data structure ตัวถัดไปก็คือ map
ลองดูคำสั่งที่เขาใช้ (เขาใช้ map keyboard code เข้ากับ ทิศทาง)
(def AsciiToDx {72 -1,
76 1,
75 0,
74 0})

เจ้าเครื่องหมาย { เป็น syntax อย่างย่อ
ถ้าจะสั่งแบบยาวหน่อย ก็ให้สั่งแบบนี้
(def AsciiToDx (hash-map 72 -1 76 1 75 0 74 0))

เครื่องหมาย comma นั้นจะใส่หรือไม่ใส่ก็ได้
(def AsciiToDx (hash-map 72 -1, 76 1, 75 0, 74 0))

การ access ค่า สามารถทำได้โดยคำสั่ง get
user> (get AsciiToDx 72)
-1


ถัดจาก map ก็คือ vector และ list
ทั้ง vector และ list จะใช้คำสั่งเหมือนกันอย่างกับแกะ ต่างกันตรง data structure ภายในที่เก็บ
เจ้า vector เวลาเรา add item เข้าไป, item นั้นจะไปต่อท้าย
ส่วน list นั้น ถ้าเรา add item เข้าไป, item จะไปอยู่ที่หัว
user> (conj '(1 2 3) 4)
(4 1 2 3)
user> (conj [1 2 3] 4)
[1 2 3 4]

Note: จะเห็นเครื่องหมาย ' ที่หน้า list (1 2 3)
เครื่องหมายนั้นจะบอก clojure ว่า (1 2 3) เป็น data นะ ไม่ต้องไป evaluate มัน

เวลาดูโปรแกรม clisp จะเห็นว่ามีเครื่องหมาย () อยู่เต็มไปหมด (ชื่อภาษามันบอกอยู่แล้วว่ามันคือ list)
แต่เจ้า clojure ที่ลอก syntax มา มีการดัดแปลง syntax ไปเล็กน้อย
โดยจะเห็นว่าเขาเอา vector มาใช้ define พวก parameter list, binding list
ซึ่งก็น่าจะทำให้ programmer recognise code ได้ไวขึ้น

Related link from Roti

Thursday, November 20, 2008

เรียนรู้ clojure - data structure

เมื่อวาน @somkiat post link http://blog.learnr.org/post/59883018/first-clojure-program ใน twiiter
ผมตามไปอ่านแล้ว รู้สึกถูกใจในขนาดและความยากที่ดูจะเหมาะแก่การเริ่มต้นเรียนรู้ Clojure

เริ่มกันที่ data structure ก่อน
ในโปรแกรมนี้เขาใช้ StructMaps ในการเก็บค่าต่างๆเช่น position ของ กำแพง,ผู้เล่น
โดย StructMaps นั้นสามารถสร้างได้โดยใช้คำสั่งู่แบบนี้
(defstruct pos :x :y)

Note: เจ้าคำสั่ง defstruct จริงๆมันเป็นแค่ macro
สิ่งที่เกิดขึ้นจริงๆ ก็คือมันจะแปลงคำสั่ง (defstruct pos :x :y) ให้เป็น (def pos (create-struct :x :y))

เวลาที่เราต้องการสร้าง data ก็ให้สั่งแบบนี้
(struct pos 1 2)

ถ้าต้องการ get ค่า x ก็ให้สั่ง
(:x (struct pos 1 2))

เนื่องจาก Clojure พยายามเน้นที่ Parallel programming
ดังนั้น struct เมื่อสร้างขึ้นมาแล้ว ก็ไม่สามารถเปลี่ยนค่าภายในได้ (immutable)
ถ้าเราต้องการเปลี่ยนค่าภายใน ก็หมายถึงว่าเราต้องสร้าง data ใหม่ขึ้นมา
ดูตัวอย่างนี้
user> (def mypos (struct pos 1 2)) ;; สร้างตัวแปร mypos ที่เก็บตำแหน่ง (1,2)
#=(var user/mypos)
user> (assoc mypos :x 10) ;; เปลี่ยนค่า x ให้เป็น 10
{:x 10, :y 2}
user> (:x mypos) ;; แสดงค่า x
1
user> (def mypos (assoc mypos :x 10)) ;; ถ้าต้องการเปลี่ยนก็หมายถึงว่าต้อง set mypos ให้ชี้ไปที่ StructMap ตัวใหม่ที่ return จาก assoc
#=(var user/mypos)
user> (:x mypos)
10


เจ้า StructMaps จริงๆแล้วก็คือ Map ที่ define keys ที่เป็นไปได้ไว้ (รวมทั้งลำดับด้วย)
เราสามารถใช้ คำสั่งต่างๆที่เกี่ยวกับ Map มาทำ operation บน StructMaps ได้หมด
เช่น
user> (vals mypos) ;; return values ของ mypos
(10 2)
user> (keys mypos) ;; return keys ของ mypos
(:x :y)


คำสั่งที่น่าสนใจ ก็คือ accessor
ที่ return function ที่ใช้ access value ของ StructMaps นั้นๆ
user> (def get-x (accessor pos :x))
#=(var user/get-x)
user> (get-x mypos)
10


ในโปรแกรมจะเห็นตัวอย่างหนึ่งที่น่าสนใจก็คือ
เขาประกาศ struct ของ level ไว้ดังนี้
(defstruct level
:player ; pos
:boxes ; set-of-pos
:goals ; set-of-pos
:walls ; set-of-pos
)

ที่น่าสนใจก็คือ ปกติถ้าเราต้องการสร้าง data ของ level เราก็ใช้คำสั่ง
(struct level a b c d) ได้
แต่การใช้คำสั่งแบบนี้ จะทำให้สับสนภายหลังได้ง่าย ว่า ตัวแปร a,b,c,d หมายถึงอะไร
ดังนั้นวิธีการที่เหมาะก็คือ ใช้คำสั่ง struct-map ในการสร้าง data แทน
(struct-map level
:player (first (filter-level expl-level \@ \+))
:boxes (filter-level expl-level \o \*)
:goals (filter-level expl-level \. \* \+)
:walls (filter-level expl-level \# \#))))

Related link from Roti