【问题标题】:Returning a list of elements occurring in both lists - SML返回两个列表中出现的元素列表 - SML
【发布时间】:2012-10-19 05:09:58
【问题描述】:

)我刚从 SML 开始,一直在尝试编写一个函数,该函数接受两个列表 L1 和 L2,并返回两个列表中出现的元素列表。这是我目前所拥有的:

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);

我不确定错误在哪里。

【问题讨论】:

    标签: list sml


    【解决方案1】:

    由于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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多