我正在做一些书本上的练习Grokking函数式编程,原始代码示例是用Scala编写的,我想用Raku重写它。
在Scala的catseffect库中,有一个类型调用IO,它是一种将副作用编码为纯值的数据类型,能够表达同步和异步计算。
以下代码打印“嘿!”两次:
import cats.effect.IO
import cats.effect.unsafe.implicits.global
object TestApp extends App {
val program: IO[Unit] = for {
_ <- IO.println("hey!")
_ <- IO.println("hey!")
} yield ()
program.unsafeRunSync()
}
我能想到的Raku中对应的数据类型是Promise,或者其他一些我还不知道的数据类型。
那么,Raku 是否有一种将副作用编码为纯值的数据类型?
Supply
。
所以FizzBuzz Raku 中的示例可能如下所示:
my Supply $s .=interval: 1;
$s .tap( -> $x { say $x });
$s.grep( * %% 3).tap( -> $ { say 'fizz' });
$s.grep( * %% 5).tap( -> $ { say 'buzz' });
sleep 16;
或与
react
-whenever
块
my Supply $s .=interval: 1;
react {
whenever $s { say $_ }
whenever $s.grep( * %% 3) { say 'fizz' }
whenever $s.grep( * %% 5) { say 'buzz' }
}