Haskell内的IO实现 [英] IO implementation inside Haskell

查看:41
本文介绍了Haskell内的IO实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

事实上,我知道我们不能独立实现IO monad,但我不知道为什么.这段代码是尝试使用功能语言来实现命令式范例的尝试.您能解释一下此示例与真实IO之间的区别吗?看来main函数实现了正确的操作顺序并保持懒惰.

I know as a fact, that we cant implement an IO monad independently, but I dont know why exactly. This code is an attempt to implement an imperative paradigm using functional language. Can you explain the difference between this example and true IO? It looks like function main implements the correct action order and remains lazy.

import System.IO.Unsafe   

data Io a = Io a 

runIO :: Io a -> a
runIO (Io a) = a

instance Monad Io where  
 return x = Io x
 Io a >>= f = f a

-- internal side effect function 
output :: Show a => a -> Io () 
output s  = return $! unsafePerformIO $ print s

----------------------------------------------------------------

mainIO :: Io ()                             
mainIO = do output "A"  
            b <- return "B"
            output b     
            output b 
            x <- return (undefined :: String)
            return undefined
            output "C"    
            head [output "C", output "C"]
            output x  
            output "D"

test = runIO mainIO 

输出:

"A"
"B"
"B"
"C"
"C"
<interactive>: Prelude.undefined

推荐答案

我不确定您要显示什么.您已经使用现有的 IO 实现作为目标,在Haskell中嵌入了 IO 的编码.

I'm not sure what you're trying to show. You've embedded an encoding of IO in Haskell, using the existing implementation of IO as a target.

关键是您使用 unsafePerformIO print ---您是从其他IO系统借用的基元.

The key is your use of unsafePerformIO and print --- primitives you're borrowing from the other IO system.

考虑:如果您没有任何其他IO系统可以依靠,该怎么办.因此,没有 print 或其他方法可以调用原始IO函数.您将如何实现IO?

Consider: what if you didn't have any other IO system to lean on. So no print or other way to call primitive IO functions. How would you implement IO?

因此,尽管可以在Haskell中以多种方式实现IO抽象,但始终必须依靠新的运行时基元函数才能实际调用操作系统来执行真正的IO.那是Haskell无法原生实现的.

So while you can implement the IO abstraction many ways in Haskell, you always have to fall on new runtime primitive functions to actually call into the operating system to do real IO. That's the bit that can't be implemented in Haskell natively.

作为参考,请参见博士学位论文效果的功能规范" ,概述了在Haskell中对IO和其他效果进行编码的各种方式,并将IO规范定义为纯功能数据类型(是您所做工作的扩展).

As a reference , see the PhD thesis "A Functional Specification of Effects", Wouter Swierstra, which gives an overview of various ways IO and other effects have been encoded in Haskell, and defines a specification of IO as a purely functional data type (kind of an extension of what you've done).

这篇关于Haskell内的IO实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆