什么是'Const'应用函子?

och*_*les 28 haskell functor applicative

我刚刚Const在文档中找到了Control.Applicative,但是我很难找到有用的地方,而不是直接使用Monoid.

我错过了什么?

pig*_*ker 27

结合使用时非常有用Traversable.

getConst . traverse Const :: (Monoid a, Traversable f) => f a -> a
Run Code Online (Sandbox Code Playgroud)

这是将一堆东西混合在一起的一般方法.它是用例这使我相信这是值得分离出一种ApplicativeMonad.我需要像通用的东西elem

elem :: Eq x => x -> Term x -> Bool
Run Code Online (Sandbox Code Playgroud)

Traversable Term通过自由变量的表示来检查参数化.我一直在改变表示形式Term,我厌倦了修改一个无数的遍历函数,其中一些正在进行累积,而不是有效的映射.我很高兴找到一个涵盖两者的抽象.


Pet*_*lák 7

正如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" john
Run Code Online (Sandbox Code Playgroud)


dav*_*420 6

当你有一个适用于all(Applicative)Functor的函数或数据结构,并希望以简并的方式重用它时,它很有用.它类似于传入const或传递id给定任意函数的函数.

Van Laarhoven镜头是根据任意Functors定义的,Const用于派生一个字段访问器(同样简单Identity地派生一个字段更新器).

Traversable 类型,正如pigworker提到的,是另一个例子.