记录 newtype
记录语法可以与 newtype
一起使用,限制条件是只有一个构造函数只有一个字段。这里的好处是自动创建一个解包 newtype 的函数。这些字段通常以 run
为单位开头,get
为 monoids,un
为其他类型。
newtype State s a = State { runState::s -> (s, a) }
newtype Product a = Product { getProduct::a }
newtype Fancy = Fancy { unfancy::String }
-- a fancy string that wants to avoid concatenation with ordinary strings
重要的是要注意,记录语法通常从不用于形成值,并且字段名称严格用于展开
getProduct $ mconcat [Product 7, Product 9, Product 12]
-- > 756