加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scalaz效果的简单控制流程

发布时间:2020-12-16 18:35:25 所属栏目:安全 来源:网络整理
导读:拿这个简单的代码: var line = "";do { println("Please enter a non-empty line: ") line = readLine()} while (line.isEmpty())println("You entered a non-empty line: " + line) 它绝对不是特别优雅,特别是对于不幸的线条范围 – 但是,我认为阅读起来非
拿这个简单的代码:

var line = "";

do {
  println("Please enter a non-empty line: ")
  line = readLine()
} while (line.isEmpty())

println("You entered a non-empty line: " + line)

它绝对不是特别优雅,特别是对于不幸的线条范围 – 但是,我认为阅读起来非常简单.

现在尝试将其直接转换为scalaz效果,我想出了:

def nonEmptyLine: IO[String] = for {
   _ <- putStrLn("Please enter a non-empty line:")
   line <- readLn
   r <- if (line.isEmpty()) nonEmptyLine else IO(line)
}  yield r


(for {
  line <- nonEmptyLine
  _ <- putStrLn("You entered a non-empty line: " + line)
} yield ()).unsafePerformIO

这让我觉得我错过了什么,因为这根本不是一种改进?我缺少一些更高阶的控制流程吗?

解决方法

你可以通过跳过for表示法并使用组合器来使这个(至少可以说是)更漂亮*>和>> =将所有内容组合在一起:

import scalaz._,Scalaz._,effect._,IO._

val prompt = putStrLn("Please enter a non-empty line:")

def report(line: String) = putStrLn("You entered a non-empty line: " + line)

def nonEmptyLine: IO[String] = prompt *> readLn >>= (
  (line: String) => if (line.isEmpty) nonEmptyLine else line.point[IO]
)

然后:

scala> (nonEmptyLine >>= report).unsafePerformIO
Please enter a non-empty line:
You entered a non-empty line: This is a test.

但总的来说,我不确定你应该期望使用scalaz.effect编写的代码比简单的命令式解决方案更简洁或更容易阅读.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读