moonbitlang / core

MoonBit's Core library
https://moonbitlang.com/
Apache License 2.0
628 stars 79 forks source link

provide multimap and defaultmap #1200

Open hackwaly opened 6 days ago

hackwaly commented 6 days ago

The usages is so widely and missing them makes developers have to write boilerplates repeatedly.

Lampese commented 6 days ago

defaultmap is?

And our map can have four versions: sorted_multimap hash_multimap immut/sorted_multimap immut/hash_multimap, which one is more necessary to do?

What about multiset?

hackwaly commented 6 days ago

A defaultmap is useful in this case:

let map = DefaultMap::new(fn (_key) { 0 })
map[non_exist_key] += 1

Programming languages with extension methods support is easy to solve the A x B problem.

trait Map[K, V] {
  get(Self, K) -> V
  set(Self, K, V) -> Unit
}

trait MultiValue[T] {
  empty() -> Self
  add(Self, T) -> Self
}

pub fn add[S: Map[K, M], K, V, M: MultiValue[V]](self: S, key: K, value: V) {
  self.set(key, self.get(key).or(M::empty()).add(value))
}
Lampese commented 2 days ago

A defaultmap is useful in this case:

let map = DefaultMap::new(fn (_key) { 0 })
map[non_exist_key] += 1

Programming languages with extension methods support is easy to solve the A x B problem.

trait Map[K, V] {
  get(Self, K) -> V
  set(Self, K, V) -> Unit
}

trait MultiValue[T] {
  empty() -> Self
  add(Self, T) -> Self
}

pub fn add[S: Map[K, M], K, V, M: MultiValue[V]](self: S, key: K, value: V) {
  self.set(key, self.get(key).or(M::empty()).add(value))
}

I agree ur idea! But a funny thing is that the map's API is inconsistent, so maybe Map trait need to do but not now until this issue resolved.