假设:
- 我知道 Haskell 鼓励用类型系统解决问题,而 Clojure 避开类型系统,更喜欢用数据结构解决问题。
{-# LANGUAGE TemplateHaskell #-}
import Control.Lens
initialState :: Game
initialState = Game
{ _score = 0
, _units =
[ Unit
{ _health = 10
, _position = Point { _x = 3.5, _y = 7.0 }
}
]
}
health :: Lens' Unit Int
health = lens _health (\unit v -> unit { _health = v })
它的目的是从数据结构中获取health
值。game
我们可以在 Clojure 中使用这样的键序列访问嵌套结构:
(def initialState {:score 0
:units {:health 10
:position {:x 3.5
:y 7.0}}})
(def health [:units :health])
(defn initialState-getter [lens]
(get-in initialState lens))
(initialState-getter health)
> 10
(defn initialState-setter [lens value]
(assoc-in initialState lens value))
(initialState-setter health 22)
> {:score 0, :units {:health 22, :position {:y 7.0, :x 3.5}}}
在这里,我们看到一个嵌套结构被一个键序列更新。
我的问题是:Haskell 中的镜头和 Clojure 中使用键序列之间有什么异同?