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

如何为带数据构造器的Haskell LST类型编写Functor实例?

为LST类型实现Functor实例

首先回顾给定的类型定义:

type ID = Int
data LST a
  = Leaf ID a
  | Node ID [LST a]
    deriving (Show, Eq)

要实现Functor实例,我们需要遵循fmap :: (a -> b) -> LST a -> LST b的类型签名,递归处理每个构造器:

instance Functor LST where
  fmap f (Leaf id val) = Leaf id (f val)
  fmap f (Node id children) = Node id (map (fmap f) children)

实现说明:

  • 对于Leaf构造器:仅对a类型的val字段应用函数f,ID类型的标识字段保持不变,因为它与类型参数a无关。
  • 对于Node构造器:同样保留ID字段不变,对子节点列表中的每个LST a元素递归应用fmap f,通过map函数遍历列表完成批量转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 09:03:19