简体   繁体   English

Scalaz和主要方法

[英]Scalaz and main method

I'm trying to learn Scalaz with a toy project of mine, I used monads in Haskell and now I want to learn how to use them in Scala with Scalaz. 我正在尝试用我的玩具项目学习Scalaz,我在Haskell中使用monad,现在我想学习如何在Scala中使用Scalaz。

The big question is, how does one use the IO() Monad in the Scala's main method? 最大的问题是,如何在Scala的main方法中使用IO() Monad?

In Haskell, the main function is of type IO() and in Scala it is of type () . 在Haskell中,main函数的类型为IO()而在Scala中,它的类型为()

The solution I found so far was to create another function foo of type IO() and in the main method call foo.unsafePerformIO() . 到目前为止我找到的解决方案是创建另一个类型为IO()函数foo ,并在main方法中调用foo.unsafePerformIO() But this makes me cringe. 但这让我感到畏缩。

What could be a solution? 什么可以解决方案?

Scalaz provides a SafeApp trait that allows you to replace Scala's side-effectful main method with a wrapper that looks more like Haskell's main : Scalaz提供了一个SafeApp特性 ,允许您使用看起来更像Haskell main的包装器替换Scala的副作用main方法:

import scalaz._, Scalaz._, effect.{ IO, SafeApp }

object MyMain extends SafeApp {
  override def runl(args: List[String]): IO[Unit] = IO(println("hello world"))
}

Now MyMain can be used like any other JVM class with a static main . 现在, MyMain可以像任何其他具有静态main JVM类一样使用。

I don't personally use SafeApp much, but it's there if you want to avoid calling unsafePerformIO by hand. 我个人并不太喜欢使用SafeApp ,但是如果你想避免手动调用unsafePerformIO ,那就在那里。

Scala's native main method is meant to be side effectful; Scala的本土主要方法是有效的; calling unsafePerformIO in it is completely safe. 在其中调用unsafePerformIO是完全安全的。

In fact, considering most Scala projects aren't 100% pure/Scalaz code, this approach is probably the most idiomatic one. 事实上,考虑到大多数Scala项目不是100%纯/ Scalaz代码,这种方法可能是最惯用的方法。 Someone might have provided an "elegance" wrapper for it, but it wouldn't add any value besides cosmetics. 有人可能会为它提供一个“优雅”的包装,但除了化妆品之外它不会增加任何价值。 And, again, most of the time you'd be embedding a Scalaz IO action inside a more mainstream, non-pure and possibly even non-functional Scala code anyway. 而且,大多数情况下,无论如何,您都要将Scalaz IO动作嵌入更主流,非纯粹甚至可能无功能的Scala代码中。

Furthermore, in general, and even in Haskell, the unsafe functions are typically just makeSureYouKnowWhatYoureDoing functions. 此外,一般情况下,甚至在Haskell中, unsafe函数通常只是makeSureYouKnowWhatYoureDoing函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM