Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List 小于标准ML中的函数_List_Types_Map_Sml - Fatal编程技术网

List 小于标准ML中的函数

List 小于标准ML中的函数,list,types,map,sml,List,Types,Map,Sml,我试图在SML中创建一个函数,它接受一个列表和一个int,并返回一个小于int的所有元素的列表int*int list->int list,我编写了以下代码: - fun less (e, L) = = map (fn a => if a < e then a else []) L; -无趣(e,L)= =映射(fn a=>如果a如果a”X列表 在表达上: foldr(fn a=>if

我试图在SML中创建一个函数,它接受一个列表和一个int,并返回一个小于int的所有元素的列表
int*int list->int list
,我编写了以下代码:

- fun less (e, L) = 
=   map (fn a => if a < e then a else []) L;
-无趣(e,L)=
=映射(fn a=>如果a
对于以下代码,它也不起作用:

- fun less (e, L) = 
=   map (fn a => if a < e then a) L;
-无趣(e,L)=
=映射(fn a=>如果a
我得到的错误是:

stdIn:22.15-22.38 Error: types of if branches do not agree [overload]
  then branch: 'Z
  else branch: 'Y list
  in expression:
    if a < e then a else nil
stdIn:22.15-22.38错误:if分支类型不一致[过载]
然后分支:“Z”
else分支:Y列表
在表达上:
如果a
我想问题出在其他部分,但我不知道该怎么做,有人有什么建议吗?我应该使用map、foldl或foldr函数

编辑:

-无趣(e,L)=
=让
=val acc=[]
=在
=foldr(fn a=>如果a
仍然给我错误,以下错误:

stdIn:241.3-241.54 Error: operator and operand don't agree [overload]
  operator domain: 'Z * 'Y -> 'Y
  operand:         'X -> 'X list
  in expression:
    foldr (fn a => if <exp> < <exp> then <exp> :: <exp> else acc)
stdIn:241.3-241.54错误:运算符和操作数不一致[重载]
运算符域:“Z*”Y->“Y”
操作数:“X->”X列表
在表达上:
foldr(fn a=>if
错误信息清晰;由于
a
具有类型
int
[]
具有类型
'a列表
,因此它们的类型不匹配

问题是您为任务选择了错误的高阶函数。列表结构上的
过滤器
最适合这里:

fun less (e, L) = filter (fn a => a < e) L

let..in..end
部分是多余的,因为您仅将
[]
用作累加器。

我应该使用其中一个映射,foldl或foldrfunction@aizen92:我的意思是使用
构造函数从元素
a
和累加器
acc
创建一个新的列表
a::acc
。是的,我计算了这一部分,但我的意思是prepend是什么,与append有什么区别?@aizen92:它将改变元素的顺序。但是,建议使用此选项,因为
是O(1),但
@
是O(n)乘以左操作数列表的长度。我已经编写了另一个代码,但我在第一篇文章中发布了空格,请检查它是否给我错误
fun less (e, L) = filter (fn a => a < e) L
fun less (e, L) = foldr (fn (a, acc) => if a < e then a::acc else acc) [] L