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 婆婆高寿祝福语大全简短