Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: “any” and “all” functions

my Haskell* is a bit rusty, so i can imagine that I’m missing the obvious:

def any[A](s: Traversable[A], f: A => Boolean): Boolean = {     s.foldLeft(false)((bool, elem) => bool || f(elem)) } 

Does one of these properties apply to the it?

  1. predefined somewhere in the Scala libs
  2. circumstantial, and faster written as some one-liner
  3. wrong (I didn’t test it, sorry ;))

*actually SML, but that’s 99% the same, but known by nobody under the sun.

like image 479
flying sheep Avatar asked Jun 17 '11 19:06

flying sheep


People also ask

What is list any in scala?

Scala Lists are quite similar to arrays which means, all the elements of a list have the same type but there are two important differences. First, lists are immutable, which means elements of a list cannot be changed by assignment. Second, lists represent a linked list whereas arrays are flat.

What are the functions in scala?

In scala, functions are first class values. You can store function value, pass function as an argument and return function as a value from other function. You can create function by using def keyword. You must mention return type of parameters while defining function and return type of a function is optional.

What does => mean in scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

What is difference between function and method in scala?

Scala functions are first class values. Difference between Scala Functions & Methods: Function is a object which can be stored in a variable. But a method always belongs to a class which has a name, signature bytecode etc. Basically, you can say a method is a function which is a member of some object.


1 Answers

  1. It's predefined and is called exists. And forall would be the "all" function you are looking for.

    scala> Vector(3, 4, 5).exists(_ % 2 == 0) res1: Boolean = true  scala> Vector(3, 4, 5).forall(_ % 2 == 0) res2: Boolean = false 
  2. You can make it more performant using a for loop with a break (from scala.util.control.Breaks). (See the standard library implementation of exists and forall.)

  3. It's correct.

like image 122
missingfaktor Avatar answered Oct 09 '22 05:10

missingfaktor