这是在 Haskell 中使用拉链的示例:
data Tree a = Fork (Tree a) (Tree a) | Leaf a
data Cxt a = Top | L (Cxt a) (Tree a) | R (Tree a) (Cxt a)
type Loc a = (Tree a, Cxt a)
left :: Loc a -> Loc a
left (Fork l r, c) = (l, L c r)
right :: Loc a -> Loc a
right (Fork l r, c) = (r, R l c)
top :: Tree a -> Loc a
top t = (t, Top)
up :: Loc a -> Loc a
up (t, L c r) = (Fork t r, c)
up (t, R l c) = (Fork l t, c)
upmost :: Loc a -> Loc a
upmost l@(t, Top) = l
upmost l = upmost (up l)
modify :: Loc a -> (Tree a -> Tree a) -> Loc a
modify (t, c) f = (f t, c)
这是在 Clojure 中使用拉链的示例:
(use 'clojure.zip)
(require '[clojure.zip :as z])
user> (def z [[1 2 3] [4 [5 6] 7] [8 9]])
#'user/z
user> (def zp (zipper vector? seq (fn [_ c] c) z))
#'user/zp
user> zp
[[[1 2 3] [4 [5 6] 7] [8 9]] nil]
user> (-> zp down)
[[1 2 3] {:l [], :pnodes [[[1 2 3] [4 [5 6] 7] [8 9]]], :ppath nil, :r ([4 [5 6] 7] [8 9])}]
user> (first (-> zp down))
[1 2 3]
这是在 Haskell 中使用 Lens 的示例:
data Person = P { name :: String
, addr :: Address
}
data Address = A { street :: String
, city :: String
, postcode :: String
}
setPostcode :: String -> Person -> Person
setPostcode pc p = p { addr = addr p { postcode = pc }}
这是在 Clojure 中使用镜头的示例。
(use 'lens)
(defrecord Address [street city postcode])
(defrecord Person [name age address])
(defrecord User [uid username identity password])
(def -postcode (mklens :postcode))
(def -city (mklens :city))
(def -street (mklens :street))
(def -address (mklens :address))
(def -age (mklens :age))
(def -name (mklens :name))
(def -uid (mklens :uid))
(def -username (mklens :username))
(def -identity (mklens :identity))
(def -password (mklens :password))
(-get -postcode home)
(-set -postcode home 500)
现在看来,lens 和 zippers 都是遍历嵌套数据结构的函数式方法。
我的问题是:镜片和拉链有什么区别?是否适合特定用例?