3

Tried running this code:

def ! : Int => Boolean = (p : Int => Boolean) => !p

Has a compilation error:

[error] value unary_! is not a member of Int => Boolean [error] def ! : Int => Boolean = (p : Int => Boolean) => !p 

error is highlighted for "!p"

Shouldn't the compiler automatically figure out that the result of p is a Boolean ?

Thanks in advance

EDIT: Based on comments, tried the following also. Have accomplished my task using other methods, nonetheless, am trying to learn how to define an unary operator

def unary_! : Int => Boolean = (p : Int => Boolean) => !(p(_))

still getting a compiler error at "!(p(_))"

5
  • Unary ! for a custom type must be named unary_! as in the error. Your p takes an Int, so !p(42). Commented Jun 26, 2016 at 0:56
  • Unary operator for what class? Commented Jun 26, 2016 at 2:44
  • It's not at all clear what you are trying to accomplish. Could you be more specific about what you want this to do? Commented Jun 26, 2016 at 5:50
  • 1
    You're not calling p. So the ! isn't negating the return value of p, but p itself, and ! isn't an operator defined for functions. Commented Jun 26, 2016 at 7:01
  • For example github.com/scala/scala/blob/v2.12.0-M4/src/library/scala/math/… Commented Jun 26, 2016 at 13:59

1 Answer 1

7

Maybe you intend something like:

scala> class C(p: Int => Boolean) { def unary_! : Int => Boolean = !p(_) } defined class C scala> val c = new C(i => i < 0) c: C = C@4d9cad9d scala> (!c)(42) res0: Boolean = true 
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice. Thanks much. Will have to figure out why this works & my attempts did not.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.