I’m a functional programming newbie.
I’d like to know how to implement numpy.where() in python, scala or haskell.
A good explanation would be helpful to me.
I’m a functional programming newbie. I’d like to know how to implement numpy.where() in
Share
In Haskell, doing it for n-dimensional lists, as the NumPy equivalent supports, requires a fairly advanced typeclass construction, but the 1-dimensional case is easy:
This is just a simple recursive procedure, examining each element of each list in turn, and producing the empty list when every list reaches its end. (Note that these are lists, not arrays.)
Here’s a simpler but less obvious implementation for 1-dimensional lists, translating the definition in the NumPy documentation (credit to joaquin for pointing it out):
To achieve the two-argument case (returning all indices where the condition is True; credit to Rex Kerr for pointing this case out), a list comprehension can be used:
It could also be written with the existing
select, although there’s not much point:And here’s the three-argument version for n-dimensional lists:
Here’s an example:
You would probably want to use a proper n-dimensional array type instead in practice, though. If you just want to use
selecton an n-dimensional list for one specific n, luqui’s advice (from the comments of this answer) is preferable:(adding more compositions of
zipWith3as n increases.)