How to check XML with monoid in Scala?

≡放荡痞女 提交于 2019-12-25 04:43:27

问题


Suppose I need to validate an input XML, e.g.

<a>
  <a1>a1a1a1</a1>
  <a2>a2a2a2</a2>
  <a3/>
</a>

I need to make sure that its root element has label "a" and children with labels "a1", "a2", "a3" and texts "a1a1a1", "a2a2a2" and "" respectively.

I can define the basic validation functions as follows:

type Status = ... // either Ok or list of error messages
type Validate[A] = A => Status
type ValidateNode = Validate[scala.xml.Node]

val label(l: String): ValidateNode = ... // trivial
val text(t: String): ValidateNode =  ... // trivial
val child(vn: ValidateNode) = ... // find such a child "c" that "vn(c)" is Ok

Since Status is a monoid (isomorphic to list) then Validate[A] is a monoid too and we can compose the validation functions with |+|

val a1: ValidateNode = label("a1") |+| text("a1a1a1")
val a2: ValidateNode = label("a2") |+| text("a2a2a2") 
val a3: ValidateNode = label("a3")
val a:  ValidateNode = label("a") |+| child(a1) |+| child(a2) |+| child(a3) 

Does it make sense ? How would you fix/improve it ?

来源:https://stackoverflow.com/questions/30803455/how-to-check-xml-with-monoid-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!