问题
I use this function to filter a list of integers. I'm beggining in SML and I don't know where is the error.
fun filter f = fn [] => []
| fn (x::xs) => if f(x)
then x::(filter f xs) else (filter f xs)
fun g(x) = if x>5 then true else false
val listTest = filter g [1, 2, 4, 6, 8, 10]
Thank you!
回答1:
Definitions with fn look like definitions with fun, but without the name and an arrow instead of =:
fn a0 => e0
| a1 => e1
| ...
This would be correct:
fun filter f = fn [] => []
| (x::xs) => if f(x)
then x::(filter f xs)
else (filter f xs)
but the common form is
fun filter _ [] = []
| filter f (x::xs) = if f x
then x :: filter f xs
else filter f xs
fun g x = x > 5
回答2:
You second fn is redundant, please remove it:
fun filter f = fn [] => []
| (x::xs) => if f(x)
then x::(filter f xs) else (filter f xs)
Then it can compile happily:
- use "a.sml";
[opening a.sml]
val filter = fn : ('a -> bool) -> 'a list -> 'a list
val g = fn : int -> bool
val listTest = [6,8,10] : int list
val it = () : unit
BTW, fun g(x) = if x>5 then true else false is not good style. fun g x = x > 5 is better
来源:https://stackoverflow.com/questions/52824554/filter-function-in-sml