2

I wanted to ensure if I could accomplish this by using reduceLeft rather than foldLeft. I am searching a given number in the List

val included = List(46, 19, 92).foldLeft(false) { (a, i) =>
| if (a) a else (i == 19)
| }
included: Boolean = true

However I want to accomplish the same using reduceLeft, is it possible?

3 Answers 3

5

The proper way to do this is

val included = List(46, 19, 92).contains(19)

But if you would insist on using reduceLeft, then you can write:

val included = List(46, 19, 92).reduceLeft { (a, b) =>
  if (b == 19) b else a
} == 19
Sign up to request clarification or add additional context in comments.

Comments

4

Not directly. The types, as is often the case, are the answer.

reduceLeft has a type sort of like:

List[A] => ((A,A) => A) => A

Given a List of A, and a function which can combine 2 A values into 1 A value, you get a single A value back.

what you could do would be something like:

val a = List(46, 19, 92).reduceLeft { (a, b) =>
 if(b == 19) b else a
}

val included = a == 19

Of course, you'd be better served using "contains" for this than either of those options.

2 Comments

contains, not exists, list contains 19 vs list exists (_ == 19)
Correct, and fixed, that's what I get for writing answers when I'm on mobile :).
0

You can't do it in a simple way. With foldLeft you can define the result type : it's the type of your accumulator so i's the type of the zero element you give as first parameter.
ReduceLeft uses the first element of your collection as the zero element of your accumulator. So the result type will be the same as the elements of the list, Int in your case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.