首页 > 解决方案 > 为什么会发生这种情况(Ocaml)

问题描述

在 Ocaml 语言中,目标是在删除重复项的同时合并(附加)两个列表。

let rec find_dup a lst =
  match lst with
    | [] -> false
    | hd::tl -> if (hd == a) then true else find_dup a tl;;
    


let rec app lst2 lst1 =
  match lst1 with
    | [] -> lst2
    | hd::tl -> if (find_dup hd lst2) then (app tl lst2)
     else hd::app tl lst2
     
     
     ;;

我有这样的代码,但是当测试用例是 app [4;5;6;7] [1;2;3;4] 时,答案应该是 [1;2;3;4;5;6;7]但我不断得到

到底是怎么回事?

标签: ocaml

解决方案


您正在为每个递归调用切换列表。

查看函数定义的参数顺序:

let rec app lst2 lst1

然后是递归函数调用:

app tl lst2

另外,只是为了挑剔,find_dup标准库中已经存在。它被称为List.mem


推荐阅读