编写一个返回列表中所有其他元素的函数

问题描述 投票:0回答:1

我想编写一个函数,它可以返回列表中的每个其他元素,如下所示 ['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;;
ocaml
1个回答
1
投票

事实上,您的代码缺少

let
并且您尚未表明您已打开
List
。如果我们通过添加
let
并完全限定
List.hd
List.tl
来修复这些小问题:

# 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;;
val remove_half : 'a list -> 'a list = <fun>

# remove_half [1; 2; 3; 4; 5; 6];;
- : int list = [1; 3; 5]

宾果游戏。它有效。

现在,可以使用模式匹配来清理它,而不是

List.hd
List.tl
。鉴于我们可以对至少有两个元素的列表的前两个元素进行模式匹配,因此不再需要布尔值。

let rec remove_half =
  function
  | x::_::xs -> x :: remove_half xs
  | lst -> lst 

可以使用

List.hd
List.tl
应用此技术。

let rec remove_half lst =
  if lst = [] || List.tl lst = [] then lst
  else 
    let x = List.hd lst in
    let xs = List.tl (List.tl lst) in
    x :: remove_half xs
© www.soinside.com 2019 - 2024. All rights reserved.