如何使用 Endomorphic 包装器修复此练习? [英] How to fix this exercise with Endomorphic wrapper?

查看:28
本文介绍了如何使用 Endomorphic 包装器修复此练习?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我之前的问题的后续.

假设我需要通过路径找到一个 XML 节点.我可以编写一个函数来按名称获取子节点

Suppose I need to find an XML node by path. I can write a function to get a child node by name

import scala.xml.{Node => XmlNode}

def child(name: String): XmlNode = Option[XmlNode] = _.child.find(_.label == name)

我用 kleisli 编写了 child 函数;例如

I compose the child functions with kleisli; e.g.

scala> val a = <a><a0><a1><a2/></a1></a0></a>
a: scala.xml.Elem = <a><a0><a1><a2/></a1></a0></a>

scala> val find01 = Kleisli(child("a0")) >=> Kleisli(child("a1"))
findAB: scalaz.Kleisli[Option,scala.xml.Node,scala.xml.Node] = Kleisli(<function1>)

scala> find01(a)
res85: Option[scala.xml.Node] = Some(<a1><a2/></a1>)

现在我正在使用内形包装器,但它不起作用:

Now I am using the endomorphic wrapper but it doesn't work:

 scala> List(child("a0"), child("a1")).foldMap(Endomorphic.endoKleisli[Option, XmlNode])
 res93: scalaz.Endomorphic[[α, β]scalaz.Kleisli[Option,α,β],scala.xml.Node] = Endomorphic(Kleisli(<function1>))

 scala> res93.run(a)
 res94: Option[scala.xml.Node] = None

你能帮忙找出错误吗?

推荐答案

在第一个示例中,您是从左到右组合 (>=>).

In the first example, you are composing left-to-right (>=>).

但是 调用 compose 方法(又名 <=<),从右到左工作.

But Endomorphic calls the compose method (a.k.a. <=<), which works right-to-left.

因此,您的第二个示例将首先捕获 ,然后在其中查找 ,这显然失败了.

So your second example would capture <a1> first, then look for <a0> inside that, which clearly fails.

有两种方法可以恢复从左到右的行为.您可以在折叠之前反转列表,或者将每个元素包装在 双重.

There are two ways to recover the left-to-right behavior. You can reverse the list before folding it, or wrap each element in a Dual.

这篇关于如何使用 Endomorphic 包装器修复此练习?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆