如何使用 _Cons 棱镜进行构图
How to compose using the _Cons prism
我正在尝试使用镜头实现一段相当简单的代码。但是,我已经达到了我希望能够从列表中添加和删除的地步。我已将其简化为以下内容:
{-# LANGUAGE TemplateHaskell, FlexibleContexts, ScopedTypeVariables #-}
module LensExample where
import qualified Control.Lens.TH as LensTH
import Control.Lens.Cons (_Cons)
import qualified Control.Lens.Fold
data StackExample = StackExample {
_internal :: [String]
} deriving (Show)
start = StackExample { _internal = ["Hello", "World"]}
LensTH.makeLenses 'StackExample
popString :: [String] -> Maybe (String, [String])
popString ss = Control.Lens.Fold.preview _Cons ss
popWithPrism :: StackExample -> Maybe (String, StackExample)
popWithPrism s = Control.Lens.Fold.preview _xxx s
我如何结合 internal
和 _Cons
生成 _xxx
?
一个可能的解决方案是:
popWithPrism :: StackExample -> Maybe (String, StackExample)
popWithPrism = preview $ internal . _Cons . alongside id (re internal)
这个想法是以内部列表为目标,用 _Cons
拆分它,并用 alongside
映射结果元组的每个部分——特别是第二个元素,以便重新应用StackExample
构造函数。
我正在尝试使用镜头实现一段相当简单的代码。但是,我已经达到了我希望能够从列表中添加和删除的地步。我已将其简化为以下内容:
{-# LANGUAGE TemplateHaskell, FlexibleContexts, ScopedTypeVariables #-}
module LensExample where
import qualified Control.Lens.TH as LensTH
import Control.Lens.Cons (_Cons)
import qualified Control.Lens.Fold
data StackExample = StackExample {
_internal :: [String]
} deriving (Show)
start = StackExample { _internal = ["Hello", "World"]}
LensTH.makeLenses 'StackExample
popString :: [String] -> Maybe (String, [String])
popString ss = Control.Lens.Fold.preview _Cons ss
popWithPrism :: StackExample -> Maybe (String, StackExample)
popWithPrism s = Control.Lens.Fold.preview _xxx s
我如何结合 internal
和 _Cons
生成 _xxx
?
一个可能的解决方案是:
popWithPrism :: StackExample -> Maybe (String, StackExample)
popWithPrism = preview $ internal . _Cons . alongside id (re internal)
这个想法是以内部列表为目标,用 _Cons
拆分它,并用 alongside
映射结果元组的每个部分——特别是第二个元素,以便重新应用StackExample
构造函数。