2012-10-17 43 views
1

)我刚刚开始使用SML,并试图编写一个函数,它带有两个列表L1和L2,并返回两个列表中出现的元素。这是我迄今为止:返回两个列表中出现的元素列表--SML

fun exists x nil = false | exists x (h::t) = (x = h) orelse (exists x t); 

    fun listAnd L1 nil = nil 
    | listAnd nil L2 = nil 
    | listAnd L1 L2 = if exists(hd(L1) L2) = true then hd(L1)::(listAnd(tl(L1) L2)) else listAnd(tl(L1) L2); 

我不太确定错误在哪里。

回答

0

由于exists是一个带两个参数的函数,所以您的错误是在两个参数之间放置额外的括号。例如,exists(hd(L1) L2)应更正为exists (hd L1) L2

我有几个建议:

  • 去除冗余= true
  • 使用[]空列表和通配符_
  • 使用图案L1而不是hdtl
匹配未使用的值

现在这是修正的功能离子:

fun listAnd _ [] = [] 
    | listAnd [] _ = [] 
    | listAnd (x::xs) ys = if exists x ys 
         then x::(listAnd xs ys) 
         else listAnd xs ys