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

如何为Church编码的Free Monad编写解包函数?(Haskell)

Implementing unWrap for Church-encoded Free Monad

First, let's get on the same page about what a Church-encoded Free Monad looks like in Haskell. It's a continuation-based newtype that wraps two handlers: one for pure values, one for functor-wrapped free monad values. Here's the standard definition:

newtype F f a = F { runF :: forall r. (a -> r) -> (f (F f a) -> r) -> r }

The unWrap Function Implementation

The unWrap function needs to peel back the Church encoding and return either the pure value (in Left) or the functor-wrapped free monad (in Right). Here's the concise implementation:

unWrap :: F f a -> Either a (f (F f a))
unWrap (F free) = free Left Right

How This Works

Let's break down the logic:

  • When your input is a pure value (built like F $ \pureHandler _ -> pureHandler myValue), the runF function will trigger the first continuation we pass. Since we're passing Left, this wraps myValue into Left myValue.
  • When your input is a free functor value (built like F $ \_ freeHandler -> freeHandler myFunctor), runF will trigger the second continuation. We're passing Right, so this wraps myFunctor into Right myFunctor.

Quick Demo Example

Let's use a simple functor to see it in action:

-- A trivial functor for testing
data TreeF a = Leaf | Node Int a deriving Functor

-- Pure value example
pure5 :: F TreeF Int
pure5 = F $ \pk _ -> pk 5

-- Free value example
freeNode :: F TreeF Int
freeNode = F $ \_ fk -> fk (Node 10 pure5)

-- Test the function
testPure = unWrap pure5       -- Returns Left 5
testFree = unWrap freeNode     -- Returns Right (Node 10 pure5)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 18:48:12