Filter function in SML

可紊 提交于 2019-12-25 00:43:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!