使用aeson-lens,我编写了这个程序,它使我非常接近我想要实现的目标:
{-# LANGUAGE OverloadedStrings #-}
import Network.HTTP.Conduit ( simpleHttp )
import Data.Aeson           ( decode
                            , Value
                            )
import Data.Maybe           ( fromJust )
import Control.Lens         ( (^.) )
import Data.Aeson.Lens      ( key, nth )
main :: IO ()
main = do
  pageContents <- simpleHttp "http://127.0.0.1:28017/baseball/team/"
  let v = decode pageContents :: Maybe Value
  let totalRowsVal = v ^. key "total_rows" :: Maybe Int
      oidVal       = v ^. key "rows" . nth 0 ^. key "_id" ^. key "$oid" :: …假设我有一个函数,它使用外部值中的其他内部值来提取一些内部值
func :: outer -> inner1 -> inner2
然后我有一个函数,使用这个inner2值在外部值和其他值之间创建一个镜头
existingLensFunc :: inner2 -> Lens' outer result
有没有办法创建另一个函数,使用inner1值在外部值和结果值之间创建一个镜头?
finalLens :: inner1 -> Lens' outer result
换句话说,有更好的方法来写这个吗?
finalLens inner1 = lens getter setter
  where setter outer result = let inner2 = func outer inner1 in set (existingLens inner2) result outer
        getter outer = let inner2 = func outer inner1 in view (existingLens inner2) outer
如果Nothing在深镜头查找/分配中遇到某个地方,是否可以设置默认值?
例如,查找:
(Just (4, 3), 2) ^. _1 . (maybe (6, 5)) . _1 == 4
(Nothing,     2) ^. _1 . (maybe (6, 5)) . _1 == 6
或者更重要的是,对于作业:
((Just (4, 3), 2) & _1 . (maybe (6, 5)) . _1 .~ 7) == (Just (7, 3), 2)
((Nothing,     2) & _1 . (maybe (6, 5)) . _1 .~ 7) == (Just (7, 5), 2)
我想以这种方式使用元组和镜头:
myfct :: ReaderT (a,b,c,d,e) m a -> ReaderT (a,c,d) m a
myfct = zoom ...
能够将输入元组修改为它的一个子集...
伪代码将是这样的:
zoom (_1,_3,_4)
我遵循了砖蛇游戏的整个教程,但我遇到了这个错误
[typecheck -Wdeferred-out-of-scope-variables] [E] • Variable not in scope:
    paused :: Lens.Micro.Type.Getting Bool Game Bool
• Perhaps you meant ‘_paused’ (line 24)
完整代码在这里https://github.com/dhilst/brick-stake-tutorial-exercice-
重要的部分是这个
{-# LANGUAGE TemplateHaskell, FlexibleContexts #-}
module Snake where
import Control.Applicative ((<|>))
import Control.Monad (guard)
import Data.Maybe (fromMaybe)
import Data.Sequence (Seq, ViewL(..), ViewR(..), (<|))
import qualified Data.Sequence as S
import Lens.Micro ((%~), (&), (.~), (^.))
import Lens.Micro.TH (makeLenses)
import Linear.V2 (V2(..), _x, _y)
import System.Random (Random(..), newStdGen)
-- Types
data Game =
  Game
    { _snake :: …考虑这些类型:
data A = A { a :: Int }
data B = B { a :: Int }  -- a again!
data C = C1 A | C2 B
有没有办法a从C物体上返回一些镜头(棱镜?)Int而不返回Maybe Int?因为使用模式匹配(好吧,或使用RecordWildCards):
case c of
  C1 c1 -> a c1
  C2 c2 -> a c2
我可以得到Int,但是有了镜头/棱镜,我想我永远都会得到Maybe Int。是否可以用镜头来完成?我的直觉是镜头不知道a访问器的“决定论” C,它不可能Maybe......
任何镜头,遍历或棱镜都会作为处理程序进行类型检查
type Handler a b 
   = forall x. (b -> Constant (Endo x) b) -> a -> Constant (Endo x) a
人们可能会声称,因为镜头允许任何Functor不是Constant镜片的唯一子集应该进行类型检查.为什么这个陈述不正确?