ocaml - 为什么会发生这种情况(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]但我不断得到
- : int 列表 = [1; 2;5个;3;6;4;7]
到底是怎么回事?
解决方案
您正在为每个递归调用切换列表。
查看函数定义的参数顺序:
let rec app lst2 lst1
然后是递归函数调用:
app tl lst2
另外,只是为了挑剔,find_dup
标准库中已经存在。它被称为List.mem
。
推荐阅读
- laravel - 在 laravel 中使用模型不起作用,但在使用路由时起作用
- vue.js - fs 包不在 nuxt 的客户端
- ethereum - 如何在 Uniswap SDK 中获取 Router02 的实例?
- python - Linux - 将 tkinter GUI 背景和前景色与系统主题颜色同步
- javascript - 使用 JavaScript 从 Web 套接字读取消息
- asp.net - ASP.net cookie:cross_zone、cross_session_id、cross_myzone
- javascript - Chrome 95 给出的“Uncaught SyntaxError: Invalid regular expression: /:\d+$/: Regular expression too large”
- ruby-on-rails - Rails - 带有 SQL 视图的 Postgres 和 JSON PG::InvalidTextRepresentation
- html - 如何使用 *ngFor 获取 json 数据 X 次
- regex - 我需要在输入键之前检索数字,并使用正则表达式检索它之前的空格