Search code examples
purescript

Filter array of arrays in purescript


Doing this in psci:

> filter (\[a,b] -> a > 1) [[1,2],[3,4]]

results in a compile error:

A case expression could not be determined to cover all inputs.

due to [a,b] possibly failing to match, which makes sense.

I know I can do this:

> :p
… let f [a, b] = a > 1
…     f _ = false
…
> filter f [[1,2],[3,4]]
[[3,4]]

but this is quite long for doing simple filters in psci repl. Is there a solution that involves less typing (including not using Array, etc.)?


Solution

  • You can use unsafePartial:

    > import Prelude
    > import Data.Array
    > import Partial.Unsafe
    > filter (unsafePartial \[a,b] -> a > 1) [[1,2],[3,4]]
    [[3,4]]
    

    I wouldn't recommend doing so outside of the REPL though, unless you've pre-sanitised the input and you're 100% sure the pattern match isn't partial!