for the identity function we have &(&1) as a shortcut, but &(true) does cause a compiler error. Understandably, since there is no way for the compiler to understand the arity of the function. So I was wondering, is there a shortcut for the “filter” function that that always returns true, ie., for
I think this is a case in which Elixir prefers the explicitness of fn _ -> true end over another form, because when writing it like this it is a lot more clear that you do nothing with the argument. (Which is exactly the error you get when typing &(true).
So I don’t think there is a shorter way, unless you define it as a named function with a short way somewhere.
Perhaps a more useful general tool would be a const function that itself produces a function that always returns a given value: const(true) = fun _ -> true, etc.
Yes, exactly. That way you can use this in more scenarios. For example, when you want to support higher order functions for calculating something in a function, let’s say a width for something, you can simply provide a const value function for the things where you would’ve ordinarily just pass a value.
The use case is for optional parameters where I want to allow filtering functionality. If no filter is set I am setting a default which is to bypass everything. Of course, there might be room for optimization as
Enum.filter(list, fn _ -> true end)
is just a waste of resources, but it makes for a better readibility to write
Enum.filter(list, filter_function)
and ensuring that there always is a filter function rather than distinguishing between no filter function and a provided filter function.
I very much like @gon782 and @NobbZ suggestions. Thanks a lot.