如何在Scala中更改此功能,以便在IntelliJ IDEA上运行时能够查看结果?
object poisson_sample_size extends App {
def main(theta1: Double, theta2: Double): Double = {
val theta1 = 0.0025
val theta2 = 0.0030
val num = 4
val den = ((theta1 + theta2) / 2) - math.sqrt(theta1 * theta2)
val x = num / den
println(x: Double)
}
}
我想检查结果是我期待的结果。考虑到我刚开始学习Scala,我不确定它是否有错误。
我试图将(num / den)
的结果归因于一个变量,然后print
变量本身,但它没有做我期望的事情。
答案 0 :(得分:6)
尝试将代码更改为以下内容:
object poisson_sample_size extends App {
val t1 = 0.0025
val t2 = 0.0030
val result = calculate(t1, t2)
println(result)
def calculate(theta1: Double, theta2: Double): Double = {
val num = 4
val den = ((theta1 + theta2) / 2) - math.sqrt(theta1 * theta2)
num / den
}
}
通过使对象扩展App
,您可以免费获得main
方法。然后,使用main
对您的自定义计算方法不是一个好主意,因为它会与真正的main
方法产生混淆,因此我将其更改为calculate
。然后,您需要确保调用calculate
方法,这可能是您在当前示例中看不到任何内容的真正原因。
答案 1 :(得分:1)
如果我理解正确,为了维护函数main
的预期结果,您只需要插入x
作为函数中的最后一个语句,该语句具有隐式return
含义在斯卡拉。
object poisson_sample_size extends App {
def main(theta1: Double, theta2: Double): Double = {
val num = 4
val den = ((theta1 + theta2) / 2) - math.sqrt(theta1 * theta2)
val x = num / den
println(x: Double)
x // same as: return x
}
val theta1 = 0.0025
val theta2 = 0.0030
main(theta1, theta2)
}
就像现在这样,你应该得到一个编译错误消息,因为println有一个Unit
返回类型,但你声明main
有一个Double
返回类型。< / p>
请注意,当您扩展App
时,您不必实施main
方法。运行应用程序时会执行object
的实际正文。请试试这个修改过的版本。
答案 2 :(得分:0)
从Imports System.IO
Public Class FneishSQLBackupServicev2
Dim backupTaken As Boolean = False
Protected Overrides Sub OnStart(ByVal args() As String)
WriteToFile("Sql automated backup service started")
Try
Timer1.Start()
Catch ex As Exception
WriteToFile(ex.StackTrace)
End Try
End Sub
Protected Overrides Sub OnStop()
WriteToFile("Sql automated backup service stopped")
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
WriteToFile("timer entered")
If Date.Now.Hour = My.Settings.AutoBackupTime Then
If backupTaken = False Then
backupTaken = True
TakeBackup()
End If
Else
backupTaken = False
End If
End Sub
Public Shared Sub WriteToFile(Message As String)
Try
Dim path As String = System.IO.Path.GetTempPath() + "\ServiceLog"
If Directory.Exists(path) = False Then
Directory.CreateDirectory(path)
End If
Dim filepath As String = System.IO.Path.GetTempPath() & "\ServiceLog\Log_" & DateTime.Now.Date.ToShortDateString.Replace("/".ToCharArray.GetValue(0), "_".ToCharArray.GetValue(0)) & ".txt"
Dim log As System.IO.StreamWriter
If File.Exists(filepath) = False Then
log = File.CreateText(filepath)
Else
log = My.Computer.FileSystem.OpenTextFileWriter(filepath, True)
End If
Message = Date.Now.ToLocalTime & vbNewLine & Message & vbNewLine
log.WriteLine(Message)
log.Close()
Catch ex As Exception
End Try
End Sub
End Class
开始,链接操作tap
可以这样使用:
Scala 2.13
避免这种构造:
import scala.util.chaining._
def f(): Int = calculate().tap(println)
tap
链接操作在返回原始值的同时对值施加了副作用(在这种情况下为def f(): Int = {
val x: Int = calculate()
println(x)
x
}
)
def tap [U](f:(A)=> U):A