Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 如何撰写;也许吧;镜头?_Haskell_Haskell Lens - Fatal编程技术网

Haskell 如何撰写;也许吧;镜头?

Haskell 如何撰写;也许吧;镜头?,haskell,haskell-lens,Haskell,Haskell Lens,如果我有一个嵌套记录的镜头,其中每个镜头都返回一个可能,我如何才能让它们进行合成,这样,如果“遍历”中的任何内容都返回一个无,那么最终的结果是一个无 data Client = Client { clientProperties :: Maybe Properties , ... } data Properties = Properties { propSmtpConfig :: Maybe SmtpConfig , ... } c :: Client

如果我有一个嵌套记录的镜头,其中每个镜头都返回一个
可能
,我如何才能让它们进行合成,这样,如果“遍历”中的任何内容都返回一个
,那么最终的结果是一个

data Client = Client
  {
    clientProperties :: Maybe Properties
  , ...
  }

data Properties = Properties
  {
    propSmtpConfig :: Maybe SmtpConfig
  , ...
  }

c :: Client 
c = undefined

smtp = c ^. (properties . smtpConfig) -- How to make these lenses compose?
编辑我尝试了很多选择,但这是我能想到的最好的选择。寻找更干净的东西:

(client ^. properties) >>= (view smtpConfig)
您可以使用。下面是一个人为的例子:

> (Just (Just 1, ()), ()) & _1 . _Just . _1 . _Just +~ 1
(Just (Just 2,()),())
就你而言,我想你想要

properties . _Just . smtpConfig . _Just

遍历
是有效的,请记住

getSmtpConfig :: Traversal' Client SmtpConfig
getSmtpConfig = properties . traverse . smtpConfig . traverse
遍历
是您在这里所能做的最好的操作-您无法获得
镜头
-因为可能没有
SmtpConfig
。(A表示“这些东西中总是有一个”,而A
遍历表示“可能有零个或多个”。)

这段代码实际上产生了与您使用的相同的
遍历
,但是如果您还没有对棱柱体进行grokked,可能会更容易理解

请注意,由于
遍历
可能找不到任何结果,因此您不能像在问题中那样使用来访问单个结果。您需要使用“安全头”操作符(aka)


听起来你可能在找。谢谢@Gurkenglas。请将此作为答复提交。这正是我所需要的。
\u Just
镜头的行为是否像Just
中的
,即如果值为
Nothing
,它是否会抛出错误?@SaurabhNanda我希望没有例外。它只是没有设置值。我不需要设置任何东西。我只需要获取。@SaurabhNanda,记住进入
lens
是通过在
Const
上下文中修改来完成的。所以从
什么都得不到。
smtp :: Maybe SmtpConfig
smtp = c^?properties.traverse.smtpConfig.traverse
client ^? properties . _Just . smtpConfig . _Just