【问题标题】:Scalaz validation NEL mkStringScalaz 验证 NEL mkString
【发布时间】:2017-03-08 09:49:09
【问题描述】:

我正在尝试学习 scalaz 验证,并给出了这段代码:

          AuthorValidator.validate(author) match {
            case scalaz.Success(authorValidated) => onSuccess(authorService.addAuthor(authorValidated)) { extract: Int =>
                complete(StatusCodes.OK -> extract+"")
              }
            case scalaz.Failure(failure) => complete(StatusCodes.Accepted, failure mkString "/") // this piece won't work
          }
        }

我想从failure : NonEmptyList[String] 获取格式化字符串。基本上,我不能使用 mkString。你知道 scalaz 是否提供了一些格式化 NEL 的方法?

【问题讨论】:

  • 你可能想看看Show typeclass eed3si9n.com/learning-scalaz/Show.html
  • 好的,谢谢,过去几天我都在经历 scalaz,我只是不记得一切了 :)
  • 我建议不要对这种事情使用 Show 类型类,因为 NonEmptyList[String] 已经有一个实例,它不会做你想要的。一般来说,我只会将Show 用于调试目的,而不是用于向用户展示数据。

标签: scala validation scalaz


【解决方案1】:

NonEmptyList 只是一个带有一个额外保证(非空)的列表,因此您始终可以安全地将其转换为普通的 Scala List 以便使用像 mkString 这样的方法:

import scalaz.NonEmptyList, scalaz.syntax.foldable._

def formatNel(nel: NonEmptyList[String]): String = nel.toList.mkString("/")

foldable 语法导入通过Foldable 实例为NonEmptyList 提供toList 方法。您也可以使用 nel.list.toList 首先转换为 scalaz.IList,但这有点冗长,并且对于大型列表可能效率较低(我不确定)。

还有很多其他方法可以直接编写,而无需转换为 Scala 列表。一种是转换为IList,然后使用interspersesuml

import scalaz.NonEmptyList, scalaz.std.string._, scalaz.syntax.foldable._

def formatNel(nel: NonEmptyList[String]): String = nel.list.intersperse("/").suml

不过,对于像格式化为字符串这样的东西,我可能会坚持使用toList.mkString,因为它清晰、熟悉,并且可能更有效,因为它不如suml 通用(尽管这在大多数情况下)。

【讨论】:

  • 谢谢,基本上我在我的代码中实现了它,在注意到 Show 已被弃用之后,我导入了可折叠文件,并隐含地看到我有能力(是的!)将它转换为列表(如果你不像你的母语那样了解scala,它有时会让人头疼:)),所以我做到了!我想回答我的问题,但我不想显得傲慢,所以我等了,谢谢你,现在我知道我的最后一个解决方案很好:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多