0

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.)?

levant pied
  • 3,886
  • 5
  • 37
  • 56

2 Answers2

4

I assume that

(including not using Array, etc.)?

means you could use tuples, or records, instead of nested arrays. Their structure is much easier to pattern match / deconstruct, e.g.:

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

As far as I know, PureScript does not support syntax for single-line case expressions (like case arr of { [a,b] -> a > 1; _ -> false }). If you need to use arrays, I think your multi-line solution is better than something like:

filter (\arr -> fromMaybe false (map (\a -> a > 1) (head arr))) [[1,2],[3,4]]

Fits into one line, but does not read very well...

stholzm
  • 3,395
  • 19
  • 31
3

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!

gb.
  • 4,629
  • 1
  • 20
  • 19