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?
*actually SML, but that’s 99% the same, but known by nobody under the sun.
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.
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.
=> 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 .
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.
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
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
.)
It's correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With