- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Re: MaxBy and other operations on empty Map.
Thu, 2012-02-02, 19:09
Er, wait, you _can_ do this with a fold, but not _that_ fold.
I retract my entire statement, and agree with HamsterofDeath that maxOrElse would be nice.
(I also would like the type of fold that would allow a maxBy, but somehow I had forgotten that it's not the default fold since maxBy is not the same as map / max.)
--Rex
On Thu, Feb 2, 2012 at 1:06 PM, Rex Kerr <ichoran@gmail.com> wrote:
I retract my entire statement, and agree with HamsterofDeath that maxOrElse would be nice.
(I also would like the type of fold that would allow a maxBy, but somehow I had forgotten that it's not the default fold since maxBy is not the same as map / max.)
--Rex
On Thu, Feb 2, 2012 at 1:06 PM, Rex Kerr <ichoran@gmail.com> wrote:
You can do that with a fold.
val max = map fold (0)((m,x) => m max {something_with_x})
If you are just calling methods, it's even shorter:
val max = map.fold(0)(_ max _.myMethod)
val max = map.maxBy(0)(_.myMethod)
It's _barely_ any shorter or clearer to have a dedicated method than to just use a fold.
I think we should just get rid of maxBy, since it cannot have any collection-specific shortcuts due to the mapping, and it isn't safe on empty collections as it is.
--Rex
I would rather get rid of maxBy, which is unsafe and has no possible shortcuts on any collection, and instead have people use folds.
On Thu, Feb 2, 2012 at 7:28 AM, Edmondo Porcu <edmondo.porcu@gmail.com> wrote:
Dear all,
is there a way to execute a maxBy on Map, which do not throw exception when the map is empty, but returns a default value?
I end up doing:
val max = if (map.isEmpty) 0 else map.maxBy {something}
Don't you think it would be useful to have a method such as
val max = map.maxBy(0){something}
I think it would be great if this will be included in the collection API...
Best Regards