简体   繁体   English

在Scala REPL中键入信息

[英]Type information in the Scala REPL

If I'm using the F# interpreter, I can define a simple function like this: 如果我正在使用F#解释器,我可以定义一个这样的简单函数:

> // Function to check if x is an integer multiple of y
> let multipleOf x y = (x % y = 0);;

val multipleOf : x:int -> y:int -> bool

If I know a function exists in the F# interpreter session but I'm unsure of its precise type, I can ask the interpreter to give me its type simply by typing the function's name: 如果我知道F#解释器会话中存在一个函数,但我不确定它的精确类型,我可以通过输入函数的名称让解释器给我它的类型:

> // I can't remember the type of the function multipleOf!
> multipleOf;;

val it : (int -> int -> bool) = <fun:it@12-1>

Clearly, this tells me that the function multipleOf is of type int->int->bool . 显然,这告诉我函数multipleOf的类型为int->int->bool I find this incredibly useful as a tool to jog my memory when working in the F# interpreter. 在F#解释器中工作时,我发现这非常有用,可以作为一种工具来慢慢记忆。

However, I can't seem to find similar functionality in Scala's REPL. 但是,我似乎无法在Scala的REPL中找到类似的功能。 I can define an equivalent function in Scala easily enough of course: 我当然可以很容易地在Scala中定义一个等效函数:

def multipleOf(x: Int, y: Int) = x % y == 0

But if I'm ten minutes on in my Scala REPL session and can't remember the type of the function, typing multipleOf gives no information about the type (in fact, it gives an error). 但是如果我在Scala REPL会话中已经十分钟并且不记得该函数的类型,则键入multipleOf不会提供有关该类型的信息(事实上,它会给出错误)。 Similarly, :type multipleOf tells me nothing useful. 同样, :type multipleOf告诉我没什么用处。

scala> val f = (i: Int, j: Int) => i % j == 0
f: (Int, Int) => Boolean = <function2>

scala> f
res2: (Int, Int) => Boolean = <function2>

scala> def multipleOf(x: Int, y: Int) = x % y == 0
multipleOf: (x: Int, y: Int)Boolean

scala> :type multipleOf(_, _)
(Int, Int) => Boolean

Yuck! 呸! This is one of those occasions where the solution to a question occurs to you just as you're about to submit the question to StackOverflow. 这就是在你将要向StackOverflow提交问题时,问题解决方案出现的情况之一。 Hopefully someone will find it useful if I answer it here myself. 希望有人会发现如果我自己在这里回答它有用。

It turns out that Scala will play ball on providing type information for functions as long as you tell it to evaluate the function as a partially evaluated function! 事实证明,只要你告诉它将函数评估为部分评估函数,Scala就会为函数提供类型信息。 In other words, the following does the trick: 换句话说,以下是诀窍:

scala> multipleOf _
res0: (Int, Int) => Boolean = <function2>

In other words, the REPL gives you information about the type of a function only if you reevaluate the function as a partially evaluated version of itself. 换句话说,只有当您将函数重新评估为自身的部分评估版本时,REPL才会为您提供有关函数类型的信息。 This seems significantly less than optimal. 这似乎远远不是最佳的。 ;-) ;-)

Perhaps somebody can mention in the comments why it's sane for Scala to approach things this way? 也许有人可以在评论中提到为什么Scala以这种方式处理事情是理智的?

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

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