Filter 在SML中编写过滤器函数定义

Filter 在SML中编写过滤器函数定义,filter,sml,Filter,Sml,我试图在sml中编写过滤器定义,而不使用filter。我几乎让代码正常工作了。当x不小于5时,我无法计算if语句的返回值 这是我的密码: fun Filter[] = [] | Filter(x::xs) = let fun lessthan x = if x < 5 then x else 0 in lessthan(x)::Filter(xs) end; fun Filter[]=[]| Filter(x::xs)= 让 乐趣小于x=如果xxval it=[0,3]:int

我试图在sml中编写过滤器定义,而不使用
filter
。我几乎让代码正常工作了。当x不小于5时,我无法计算
if
语句的返回值

这是我的密码:

fun Filter[] = [] | Filter(x::xs) =
let
 fun lessthan x = if x < 5 then x else 0 
in
  lessthan(x)::Filter(xs)
end;
fun Filter[]=[]| Filter(x::xs)=
让
乐趣小于x=如果x<5,则x等于0
在里面
lessthan(x)::过滤器(xs)
结束;

正如约翰·科尔曼(John Coleman)所说,过滤函数应该将其谓词(一个
'a->bool
函数)作为输入参数,并调用它,而不是内置谓词。否则,您的筛选函数将只适用于非常特定的事情,您需要一直重新定义它

本质上,只有当某些条件为真时,才希望在结果中包含
x
。所以你不能写
lessthan(x)::Filter(xs)
,因为这意味着它总是被包括在内。您当前正试图通过使用
lessthan(x)
return
0
来“不包含它”。但这意味着结果会被你无法区分的零弄乱

例如:
过滤器[0,1,6]
变成
[0,1,0]
;现在,在过滤之前,您不再知道哪个零是零。在本例中,理想情况下,过滤应该为您提供
[0,1]

提示:

  • 将if-then-else移到
    过滤器的主定义中,而不是在谓词中
  • 仅在true分支中使用
    运算符。但是在两个分支中调用
    过滤器
  • 以下是一个模板:

    fun filter p [] = []
      | filter p (x::xs) =
          if (* some condition that shouldn't just be 'lessthan' *)
          then (* something with '::' and also with 'x' and 'filter p xs' *)
          else (* something without '::' but still with 'filter p xs' *)
    
    您可以这样调用该代码:

    - fun lessthan5 x = x < 5;
    - filter lessthan5 [0,3,5,9];
    > val it = [0,3] : int list
    
    -fun lessthan5x=x<5;
    -过滤器小于5[0,3,5,9];
    >val it=[0,3]:int list
    
    或者使用匿名函数:

    - filter (fn x => x < 5) [0,3,5,9];
    > val it = [0,3] : int list
    
    -过滤器(fnx=>x<5)[0,3,5,9];
    >val it=[0,3]:int list
    

欢迎使用堆栈溢出!当问题陈述只是简单的时,很难提供解决方案。请你的问题更完整地描述一下你预期会发生什么,以及这与实际结果有什么不同。请参阅,以获取关于什么是好的解释的提示。如果您试图“对过滤器定义进行编码”,那么为什么要硬连接特定谓词(
x<5
)?
filter
函数的用途不仅仅是返回列表中少于5个元素
List.filter
的类型为
fn:('a->bool)->'a List->'a List
但您似乎试图创建类型为
int List->int.List
的函数。