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

OCaml正则表达式偏导代码报错:类型不匹配问题求助

Fixing the Type Mismatch in Your OCaml Regex Partial Derivative Function

Let's break down the type error you're seeing and fix it step by step.

Root Cause of the Type Mismatch

Your pd function's definition has a parameter ordering issue that's causing its type to diverge from what you expect:

let rec pd a re = function 
(* ... pattern matches ... *)

Here, function is an anonymous function that expects an additional regexp argument. But you've already passed re as a parameter to pd, which means the function's type ends up being:

char -> regexp -> regexp -> ReS.t

Instead of your intended:

char -> regexp -> ReS.t

When you call pd a r in the U (r, s) case, you're only supplying the first two arguments—this returns a function waiting for a third regexp parameter, not the ReS.t set that ReS.union expects. That's exactly why you get the error: "This expression has type regexp -> ReS.t but an expression was expected of type ReS.t".

Fix 1: Remove the Redundant re Parameter

Simplify the function to use function directly for the regexp pattern matching, keeping a as the first parameter:

let rec pd a = function
| V | E -> ReS.empty
| C b when b = a -> ReS.singleton E
| C b -> ReS.empty
| U (r, s) -> ReS.union (pd a r) (pd a s)
| P (r, s) when ewp r -> ReS.union ((pd a r) *.* s) (pd a s)
| P (r, s) -> (pd a r) *.* s
| S r as re -> (pd a r) *.* re ;;

Fix 2: Use match re with Instead of function

If you prefer to keep the re parameter explicit, replace function with a match expression on re:

let rec pd a re =
match re with
| V | E -> ReS.empty
| C b when b = a -> ReS.singleton E
| C b -> ReS.empty
| U (r, s) -> ReS.union (pd a r) (pd a s)
| P (r, s) when ewp r -> ReS.union ((pd a r) *.* s) (pd a s)
| P (r, s) -> (pd a r) *.* s
| S r as re -> (pd a r) *.* re ;;

Bonus: Fix a Likely Typo

I noticed a potential mistake in your P (r, s) case: you wrote ewp a, but a is a char, and ewp (which I assume checks if a regexp matches epsilon) should take a regexp argument. This should almost certainly be ewp r to check if the left-hand side of the concatenation can match the empty string—this is a core part of the partial derivative rule for concatenated regexps.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 21:12:55