I've started learning Gleam and am trying to implement a simple filter function to learn more about the language and its syntax. I saw that you can use case statements with safeguards, but when I tried on my code, I ran into a syntax error that I could not find how to solve. Do you have any tips on how I can fix this mistake?
This is the code:
pub fn filter(list: List(a), function: fn(a) -> Bool) -> List(a) {
case list {
[] -> []
[h, ..t] if function(h) -> [h, ..filter(t, function)]
[h, ..t] if !function(h) -> filter(t, function)
}
}
And this is the error message from the compiler:
error: Syntax error
┌─ src/list_ops.gleam:12:25
│
12 │ [h, ..t] if function(h) -> [h, ..filter(t, function)]
│ ^ I was not expecting this
Expected one of:
"->"
Hint: Did you mean to wrap a multi line clause in curly braces?
From the Guards section of the The Gleam Language Tour:
This restriction of not calling functions in guards is to avoid side effects in pattern matching since any function may be impure, e.g., it can perform an I/O operation.
You can just pattern-match again on the result of
function(h):