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

Haskell编写元组左右结合性等价转换函数遇解析错误求助

解决元组结合性等价的Haskell函数问题

首先,你当前的代码语法本身没问题,但可以用更直观的嵌套模式匹配简化实现,同时避免手动调用fst和snd:

-- 右结合形式转左结合形式
lAssociation :: (a, (b, c)) -> ((a, b), c)
lAssociation (a, (b, c)) = ((a, b), c)

这种写法直接解构输入的嵌套元组结构,一步构造出目标形式,逻辑更清晰。

反过来,左结合形式转右结合形式的函数可以这么写:

-- 左结合形式转右结合形式
rAssociation :: ((a, b), c) -> (a, (b, c))
rAssociation ((a, b), c) = (a, (b, c))

为什么这两个函数能证明等价性?

要证明两种结合形式等价,只需验证它们可以互相转换,且往返转换后能得到原输入:

  • 调用 rAssociation . lAssociation 会得到恒等函数:对任意输入 x :: (a, (b, c)),rAssociation (lAssociation x) == x
  • 同理,lAssociation . rAssociation 也是恒等函数:对任意输入 y :: ((a, b), c),lAssociation (rAssociation y) == y

你之前尝试的let-in其实没必要,模式匹配已经足够简洁地完成解构和构造。如果一定要用let-in,可以写成这样:

lAssociation :: (a, (b, c)) -> ((a, b), c)
lAssociation input = let (a, bc) = input
                         (b, c) = bc
                     in ((a, b), c)

另外,你提到的解析错误如果不是这段代码的问题,可能是文件中其他位置的语法错误,或者缩进不符合Haskell要求(函数体需与等号保持对齐)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:01:03