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

Haskell多参数函数的无点式实现问题求助

Haskell无点式实现解析

先看原代码定义:

data Person = Person String Int deriving ( Show, Eq )
data Animal = Animal Person deriving ( Show, Eq )

f :: String -> Int -> Animal
f s = Animal . Person s

问题解析与正确无点式写法

你尝试的[1]写法 f = Animal . Person 其实是正确的无点式实现,类型和功能完全匹配原函数。

之所以会觉得失败,大概率是测试时的误解——Animal . Person 的类型推导结果为 String -> Int -> Animal,和 f 的签名完全一致。调用 f "ppp" 8 时,Person 先接收 "ppp" 得到 Int -> Person,再和 Animal 组合,最终返回 Animal (Person "ppp" 8),和原函数结果完全相同。

错误尝试分析

  • [2] f = Animal $ Person:$ 是函数应用运算符,这里会直接把 Person 函数传给 Animal,但 Animal 需要的是 Person 类型的实例而非函数,因此类型不匹配,编译报错。
  • [3] f = Animal . (uncurry Person) . (,):写法本身可行,但属于冗余实现——先把两个参数打包成元组,再通过 uncurry 解开传给 Person,完全没必要,远不如 Animal . Person 简洁。

核心逻辑

原函数 f s = Animal . Person s 本质是 \s x -> Animal (Person s x),而 Animal . Person 等价于 \s x -> Animal (Person s x),完全符合无点式的要求——不需要显式写出参数 s 和 x。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 08:02:35