我刚刚在Control.Applicative的文档中找到了Const,但是我很难弄清楚它在哪里有用,而不是直接使用Monoid。
我遗漏了什么?
发布于 2012-07-18 07:32:29
当与Traversable结合使用时,它非常有用。
getConst . traverse Const :: (Monoid a, Traversable f) => f a -> a这是将一堆东西组合在一起的一般方法。这是使我确信值得将Applicative从Monad中分离出来的用例之一。我需要像泛化elem这样的东西
elem :: Eq x => x -> Term x -> Bool发生-检查由自由变量的表示形式参数化的Traversable Term。我一直在改变Term的表示,我受够了修改无数遍历函数,其中一些是累加,而不是有效的映射。我很高兴找到了一个涵盖了这两个方面的抽象。
发布于 2012-07-18 18:33:16
当你有一个适用于所有(Applicative) Functor的函数或数据结构,并且希望以退化的方式重用它时,它很有用。它类似于将const或id传递给给定任意函数的函数。
Van Laarhoven lenses是根据任意函数式定义的,并使用Const派生字段访问器(以及同样简单的Identity派生字段更新器)。
正如pigworker提到的那样,Traversable类型是另一个例子。
发布于 2012-10-10 23:07:53
正如dave4420提到的,为Van Laarhoven镜头实现存取器和更新器涉及到Const函数器。详述:
{-# LANGUAGE Rank2Types #-}
import Control.Applicative
import Control.Monad.Identity
-- The definition of Van Laarhoven lenses:
type Lens a b = forall f . Functor f => (b -> f b) -> (a -> f a)
-- Getter passes the Const functor to the lens:
get :: Lens a b -> a -> b
get l = getConst . (l Const)
-- Updater passes the Identity functor to the lens:
modify :: Lens a b -> (b -> b) -> (a -> a)
modify l f = runIdentity . l (Identity . f)
set :: Lens a b -> b -> (a -> a)
set l r = modify l (const r)
-- Example: -------------------------------------------
data Person = Person { _name :: String, _age :: Int }
deriving Show
name :: Lens Person String
name f (Person n a) = fmap (\x -> Person x a) (f n)
age :: Lens Person Int
age f (Person n a) = fmap (\x -> Person n x) (f a)
main :: IO ()
main = do
let john = Person "John" 34
print $ get age john
print $ set name "Pete" johnhttps://stackoverflow.com/questions/11532050
复制相似问题