This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Using map to switch List[Boolean] values

1 reply
John 4
Joined: 2012-02-19,
User offline. Last seen 42 years 45 weeks ago.

I'm trying to write a short function to take a List[Boolean] and
simply switch the values from true to false or vice versa.

Something like this:

def boolNot(myList: List[Boolean]): List[Boolean] =
myList.map ( myList: List[Boolean] => !myList)

Scala doesn't like the !myList at the end. Can anybody suggest how I
can write this to have the function simply negate each element in the
list?

Thanks.

ichoran
Joined: 2009-08-14,
User offline. Last seen 2 years 3 weeks ago.
Re: Using map to switch List[Boolean] values
Map takes a function that maps from items _inside_ the list to other items inside, not a function of the whole list!

So it's just
  myList.map(b: Boolean => !b)
which doesn't really need the type annotation (there's only one thing it can be)
  myList.map(b => !b)
or if you use the underscore abbreviation for a completely unambiguous parameter,
  myList.map(!_)

--Rex

On Sat, Feb 18, 2012 at 11:46 PM, John <john.public66@gmail.com> wrote:
I'm trying to write a short function to take a List[Boolean] and
simply switch the values from true to false or vice versa.

Something like this:

 def boolNot(myList: List[Boolean]): List[Boolean] =
     myList.map ( myList: List[Boolean] => !myList)

Scala doesn't like the !myList at the end. Can anybody suggest how I
can write this to have the function simply negate each element in the
list?

Thanks.

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland