You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写仅用List.hd/List.tl/List.length的隔元素取列表元素函数

实现OCaml隔位取列表元素的函数问题解析

需求很明确:写一个函数,返回列表里的隔位元素(取第1、3、5...个元素),比如输入['a'; 'b'; 'c'; 'd'; 'e'],要返回['a'; 'c'; 'e'],而且只能用List.hd、List.tl或List.length这三个预定义函数。

你写的代码如下:

remove_half l =
  let rec rm_half n l =
    if l = [] then []
    else
      let fst = hd l in
      let rest = tl l in
      if n then fst :: (rm_half (not n) rest) 
      else (rm_half (not n) rest) 
  in
  rm_half true l;;

代码存在的问题

最直接的两个问题:

  1. 语法缺失:OCaml函数定义必须以let开头,你漏写了let remove_half l =里的let关键字;
  2. 模块前缀遗漏:hd和tl属于List模块,默认不会全局暴露,直接调用会触发「未绑定值」的错误,必须加上List.前缀。

修正后的代码

let remove_half l =
  let rec rm_half n l =
    if l = [] then []
    else
      let fst = List.hd l in
      let rest = List.tl l in
      if n then fst :: rm_half (not n) rest
      else rm_half (not n) rest
  in
  rm_half true l;;

测试验证

用你的测试用例运行:

remove_half ['a'; 'b'; 'c'; 'd'; 'e'];;
(* 返回结果:- : char list = ['a'; 'c'; 'e'] *)

核心逻辑是对的:通过递归时切换n的布尔值,精准控制是否保留当前元素,完美实现隔位取元素的需求。

内容的提问来源于stack exchange,提问作者user21450992

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 22:17:05