Haskell免费monad将monadic计算拆分为数据结构和解释器
示例
例如,涉及从提示符读取和写入命令的计算:
首先,我们将计算的“命令”描述为Functor数据类型
{-# LANGUAGE DeriveFunctor #-}
data TeletypeF next
= PrintLine String next
| ReadLine (String -> next)
deriving Functor然后我们使用Free创建“FreeMonadoverTeletypeF”并构建一些基本操作。
import Control.Monad.Free (Free, liftF, iterM) type Teletype = Free TeletypeF printLine :: String -> Teletype () printLine str = liftF (PrintLine str ()) readLine :: Teletype String readLine = liftF (ReadLine id)
由于Freef是Monad只要f是一个Functor,我们可以使用标准Monad组合程序(包括do符号)来构建Teletype计算。
importControl.Monad-- we can use the standard combinators echo :: Teletype () echo = readLine >>= printLine mockingbird :: Teletype a mockingbird = forever echo
最后,我们编写一个“解释器”,将Teletypea值转换为我们知道如何使用的东西,例如IOa
interpretTeletype :: Teletype a -> IO a interpretTeletype = foldFree run where run :: TeletypeF a -> IO a run (PrintLine str x) = putStrLn *> return x run (ReadLine f) = fmap f getLine
我们可以用来“运行”Teletypea计算IO
> interpretTeletype mockingbird hello hello goodbye goodbye this will go on forever this will go on forever
热门推荐
10 送给表姐中秋祝福语简短
11 宝贝生日祝福语简短独特
12 圣诞祝福语大全简短星座
13 幼园开学简短祝福语
14 牛年企业祝福语简短大气
15 新年至客户祝福语简短
16 物业小区高考祝福语简短
17 朝鲜元旦祝福语大全简短
18 闺蜜小孩祝福语简短