JuliaLang / julia

The Julia Programming Language
https://julialang.org/
MIT License
45.55k stars 5.47k forks source link

Define map for Sets #51703

Open schlichtanders opened 11 months ago

schlichtanders commented 11 months ago
julia> map(identity, Set([1,2,3]))
ERROR: map is not defined on sets
Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:35
 [2] map(f::Function, #unused#::Set{Int64})
   @ Base ./abstractarray.jl:3294
 [3] top-level scope
   @ REPL[39]:1

I know that there is an ongoing discussion about what map should do on Dicts and that there is also a similar closed issue which combined Set/Dict, but really, reading through it does not seem to give any argument why map should not be defined for Sets.

I guess the discussion for Set is what the semantics of map is:

  1. whether it should always return a fixed type (like Python's map)
  2. or whether map follows the general functor semantics (found e.g. in haskell or Scala), which means that map returns the same parent type which the input has.

Let's go for functor semantics (2.) - some thoughts

While for Dict semantics 2 are not really clear in julia, because a dict may be understood as a vector of pairs or some fancy indexed values, for Set the semantics 2 is indeed crystal clear.

map(x -> x+1, Set([1,2,3])) would return Set([2,3,4]) when following semantic 2.

Also within Julia's standard library the SparseVector notably follow semantics 2:

map(x -> x+1, sparse([1,2,0])) returns a SparseVector

I would also like to argue that, in general, for julia having multiple dispatch it makes far more sense to follow the functor semantics (2.).

Conclusion

Although the discussion for Dict is not resolved, it makes sense to define map for Set in julia.

jariji commented 11 months ago

Related: https://github.com/JuliaLang/julia/issues/32081, https://github.com/JuliaLang/julia/issues/33701, https://github.com/JuliaLang/julia/issues/38344