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

OCaml新手求助:修复模式匹配不完整的destutter去重函数

Fixing the "Pattern Matching Not Exhaustive" Issue in Your OCaml destutter Function

Hey there! Let's walk through how to fix that pattern matching error you're hitting. The problem here is that your current code only accounts for two specific cases of a list: an empty list, and a list with at least two elements. You're missing the case where the list has exactly one element—OCaml requires you to cover all possible list patterns to avoid that warning!

What's Missing?

In OCaml, every non-empty list falls into one of two buckets:

  • A single element followed by an empty list (hd :: []), or
  • An element followed by another non-empty list (hd1 :: hd2 :: tl)

Your original code skips the first scenario, so when you pass a list like [5], OCaml doesn't have a rule to handle it, hence the "not exhaustive" warning.

Updated Code with Complete Pattern Matching

Here's how to adjust your function to cover all cases properly:

(* Remove contiguous duplicates from a list *)
let rec destutter list =
  match list with
  | [] -> []
  | hd :: [] -> [hd]  # Handle single-element lists—no duplicates possible here!
  | hd1 :: hd2 :: tl ->
      if hd1 = hd2 then destutter (hd2 :: tl)
      else hd1 :: destutter (hd2 :: tl)

How This Works

  • For an empty list ([]), we just return an empty list—there's nothing to process.
  • For a single-element list (hd :: []), there's no element after it to form a duplicate, so we return the list as-is.
  • For lists with two or more elements, we check if the first two elements are equal:
    • If they are, we skip the first element and recurse with the rest of the list.
    • If not, we keep the first element and recurse with the rest of the list to check for further duplicates.

Quick Test Cases to Verify

Let's make sure this works as expected:

  • destutter [1;1;2;2;3] → [1;2;3]
  • destutter [5] → [5]
  • destutter [] → []
  • destutter ["a";"a";"a"] → ["a"]

That should resolve the pattern matching warning and make your function work for all valid list inputs!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:05:48