Haskell:不同语言的实际IO单子实现?

16

IO Monad的实现是什么?也就是说,main函数的实际实现是什么?

我如何从另一种语言中调用Haskell函数(IO),在这种情况下,我是否需要自己维护IO?

main会以惰性方式提取IO操作作为引用,然后调用它们吗?还是这是解释器的工作,当它发现操作时,才会调用它们?还是其他原因?

是否有其他语言中很好的IO Monad实现可以帮助深入理解主要功能?

编辑:

hGetContents等函数让我感到困惑,并使我不确定IO的实际实现方式。

好的,假设我有一个非常简单的纯Haskell解释器,不幸的是它没有IO支持,出于好奇心,我想将IO操作添加到其中(使用unsafeIO技巧)。从GHC、Hugs或其他地方获取它很困难。


7
顺便问一下,你已经阅读过http://www.haskell.org/haskellwiki/IO_inside这篇文章了吗? - hvr
是的,很多次了。您能告诉我哪个部分可以帮助我解决问题吗?当它说(...我应该说,我这里并没有准确描述什么是单子(我自己甚至也不完全理解),我的解释只展示了一种在Haskell中实现IO单子的_可能_方式。例如,hbc Haskell编译器通过延续实现IO单子...)时,更加混乱。 - KA1
4
忽略hGetContents。它使用unsafeInterleaveIO实现,该函数在幕后进行一些诡计以允许惰性I/O。它不是IO应该工作的好例子。 - C. A. McCann
1
如果你想知道IO是如何真正实现的,可以从这个主题的论文开始:http://research.microsoft.com/en-us/um/people/simonpj/papers/lazy-functional-state-threads.ps.Z - Carl
谢谢你,@Carl,这篇论文很有趣。 - KA1
8个回答

28

以下是在Java中实现IO Monad的示例:

package so.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import static so.io.IOMonad.*;  
import static so.io.ConsoleIO.*;    

/**
 * This is a type containing no data -- corresponds to () in Haskell.
 */
class Unit {
    public final static Unit VALUE = new Unit(); 
}

/**
 * This type represents a function from A to R
 */
interface Function<A,R> {
    public R apply(A argument);
}

/**
 * This type represents an action, yielding type R
 */
interface IO<R> {
    /**
     * Warning! May have arbitrary side-effects!
     */
    R unsafePerformIO();
}

/**
 * This class, internally impure, provides pure interface for action sequencing (aka Monad)
 */
class IOMonad {
    static <T> IO<T> pure(final T value) {
        return new IO<T>() {
            @Override
            public T unsafePerformIO() {
                return value;
            }
        };
    }

    static <T> IO<T> join(final IO<IO<T>> action) {
        return new IO<T>(){
            @Override
            public T unsafePerformIO() {
                return action.unsafePerformIO().unsafePerformIO();
            }
        };
    }

    static <A,B> IO<B> fmap(final Function<A,B> func, final IO<A> action) {
        return new IO<B>(){
            @Override
            public B unsafePerformIO() {
                return func.apply(action.unsafePerformIO());
            }
        };
    }

    static <A,B> IO<B> bind(IO<A> action, Function<A, IO<B>> func) {
        return join(fmap(func, action));
    }
}

/**
 * This class, internally impure, provides pure interface for interaction with stdin and stdout
 */
class ConsoleIO {
    static IO<Unit> putStrLn(final String line) {
        return new IO<Unit>() {
            @Override
            public Unit unsafePerformIO() {
                System.out.println(line);
                return Unit.VALUE;
            }
        };
    };

    // Java does not have first-class functions, thus this:
    final static Function<String, IO<Unit>> putStrLn = new Function<String, IO<Unit>>() {
        @Override
        public IO<Unit> apply(String argument) {
            return putStrLn(argument);
        }
    };

    final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    static IO<String> getLine = new IO<String>() {
            @Override
            public String unsafePerformIO() {
                try {
                    return in.readLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };
}

/**
 * The program composed out of IO actions in a purely functional manner.
 */
class Main {

    /**
     * A variant of bind, which discards the bound value.
     */
    static IO<Unit> bind_(final IO<Unit> a, final IO<Unit> b) {
        return bind(a, new Function<Unit, IO<Unit>>(){
            @Override
            public IO<Unit> apply(Unit argument) {
                return b;
            }
        });
    }

    /**
     * The greeting action -- asks the user for his name and then prints a greeting
     */
    final static IO<Unit> greet = 
            bind_(putStrLn("Enter your name:"), 
            bind(getLine, new Function<String, IO<Unit>>(){
                @Override
                public IO<Unit> apply(String argument) {
                    return putStrLn("Hello, " + argument + "!");
                }
            }));

    /**
     * A simple echo action -- reads a line, prints it back
     */
    final static IO<Unit> echo = bind(getLine, putStrLn);

    /**
     * A function taking some action and producing the same action run repeatedly forever (modulo stack overflow :D)
     */
    static IO<Unit> loop(final IO<Unit> action) {
        return bind(action, new Function<Unit, IO<Unit>>(){
            @Override
            public IO<Unit> apply(Unit argument) {
                return loop(action);
            }
        });
    }

    /**
     * The action corresponding to the whole program
     */
    final static IO<Unit> main = bind_(greet, bind_(putStrLn("Entering the echo loop."),loop(echo)));
}

/**
 * The runtime system, doing impure stuff to actually run our program.
 */
public class RTS {
    public static void main(String[] args) {
        Main.main.unsafePerformIO();
    }
}

这是一个运行时系统,实现了与控制台I/O的接口,以及一个小型的纯函数程序,它向用户问候,然后运行回声循环。

由于Haskell是一种纯函数语言,因此无法在其中实现不安全的部分。它总是使用更低级别的设施来实现。


11

使用Java 8的Lambda表达式,您可以采用Rotsor上面的代码,删除Function类,因为Java 8提供了FunctionalInterface的功能,可以实现相同的功能,并删除匿名类冗余代码,从而实现更加简洁的代码,如下所示:

package so.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.function.Function;

import static so.io.IOMonad.*;
import static so.io.ConsoleIO.*;

/**
 * This is a type containing no data -- corresponds to () in Haskell.
 */
class Unit {

   // -- Unit$

   public final static Unit VALUE = new Unit();

   private Unit() {
   }

}

/** This type represents an action, yielding type R */
@FunctionalInterface
interface IO<R> {

   /** Warning! May have arbitrary side-effects! */
   R unsafePerformIO();

}

/**
 * This, internally impure, provides pure interface for action sequencing (aka
 * Monad)
 */
interface IOMonad {

   // -- IOMonad$

   static <T> IO<T> pure(final T value) {
      return () -> value;
   }

   static <T> IO<T> join(final IO<IO<T>> action) {
      return () -> action.unsafePerformIO().unsafePerformIO();
   }

   static <A, B> IO<B> fmap(final Function<A, B> func, final IO<A> action) {
      return () -> func.apply(action.unsafePerformIO());
   }

   static <A, B> IO<B> bind(IO<A> action, Function<A, IO<B>> func) {
      return join(fmap(func, action));
   }

}

/**
 * This, internally impure, provides pure interface for interaction with stdin
 * and stdout
 */
interface ConsoleIO {

   // -- ConsoleIO$

   static IO<Unit> putStrLn(final String line) {
      return () -> {
         System.out.println(line);
         return Unit.VALUE;
      };
   };

   final static Function<String, IO<Unit>> putStrLn = arg -> putStrLn(arg);

   final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

   static IO<String> getLine = () -> {
      try {
         return in.readLine();
      }

      catch (IOException e) {
         throw new RuntimeException(e);
      }
   };

}

/** The program composed out of IO actions in a purely functional manner. */
interface Main {

   // -- Main$

   /** A variant of bind, which discards the bound value. */
   static IO<Unit> bind_(final IO<Unit> a, final IO<Unit> b) {
      return bind(a, arg -> b);
   }

   /**
    * The greeting action -- asks the user for his name and then prints 
    * greeting
    */
   final static IO<Unit> greet = bind_(putStrLn("Enter your name:"),
         bind(getLine, arg -> putStrLn("Hello, " + arg + "!")));

   /** A simple echo action -- reads a line, prints it back */
   final static IO<Unit> echo = bind(getLine, putStrLn);

   /**
    * A function taking some action and producing the same action run repeatedly
    * forever (modulo stack overflow :D)
    */
   static IO<Unit> loop(final IO<Unit> action) {
      return bind(action, arg -> loop(action));
   }

    /** The action corresponding to the whole program */
    final static IO<Unit> main = bind_(greet, bind_(putStrLn("Entering the echo loop."), loop(echo)));

}

/** The runtime system, doing impure stuff to actually run our program. */
public interface RTS {

    // -- RTS$

    public static void main(String[] args) {
       Main.main.unsafePerformIO();
    }

 }

请注意,我还将类声明的静态方法更改为接口声明的静态方法。为什么?没有特别的原因,只是在Java 8中可以这样做。


2
谢谢,lambda确实让代码看起来更漂亮!但是那些看似毫无意义的注释,比如// -- Unit$是什么意思呢?它们看起来不像javadoc。是什么解释了它们? - Rotsor

9

如果你想了解IO单子的实现,可以阅读Phil Wadler和Simon Peyton Jones撰写的屡获殊荣的论文。他们是第一批发现如何在纯语言中使用单子来进行输入/输出操作的人。这篇论文名为Imperative Functional Programming,可以在两位作者的网站上找到。


6

以下是GHC 7.10中IO的实际实现。

IO类型本质上是一个状态单子,其类型为State# RealWorld (GHC.Types中定义):

{- |
A value of type @'IO' a@ is a computation which, when performed,
does some I\/O before returning a value of type @a@.
There is really only one way to \"perform\" an I\/O action: bind it to
@Main.main@ in your program.  When your program is run, the I\/O will
be performed.  It isn't possible to perform I\/O from an arbitrary
function, unless that function is itself in the 'IO' monad and called
at some point, directly or indirectly, from @Main.main@.
'IO' is a monad, so 'IO' actions can be combined using either the do-notation
or the '>>' and '>>=' operations from the 'Monad' class.
-}
newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))

IO单子是严格的,因为bindIO是通过case匹配来定义的(GHC.Base中定义):

instance  Monad IO  where
    {-# INLINE return #-}
    {-# INLINE (>>)   #-}
    {-# INLINE (>>=)  #-}
    m >> k    = m >>= \ _ -> k
    return    = returnIO
    (>>=)     = bindIO
    fail s    = failIO s

returnIO :: a -> IO a
returnIO x = IO $ \ s -> (# s, x #)

bindIO :: IO a -> (a -> IO b) -> IO b
bindIO (IO m) k = IO $ \ s -> case m s of (# new_s, a #) -> unIO (k a) new_s

这个实现在Edward Yang的博客文章中讨论。


6
IO单子基本上是作为状态变换器实现的(类似于State),其中有一个特殊的标记RealWorld。每个IO操作都依赖于这个标记,并在完成时传递它。unsafeInterleaveIO引入了第二个标记,以便在另一个IO操作仍在执行其工作时可以启动新的IO操作。
通常,您不必关心实现细节。如果您想从其他语言调用IO函数,则GHC会负责删除IO包装器。考虑下面这个小片段:
printInt :: Int -> IO ()
printInt int = do putStr "The argument is: "
                  print int

foreign export ccall printInt :: Int -> IO ()

这将生成一个符号,用于从C语言中调用printInt。该函数变为:
extern void printInt(HsInt a1);

在你的平台上,HsInt只是一个 inttypedef。因此,可以看到,单子 IO 已完全被移除。


3
事实上,“IO a”在不纯的语言中只是“() -> a”(其中函数可以具有副作用)。假设您想在SML中实现IO:
structure Io : MONAD =
struct
  type 'a t = unit -> 'a
  return x = fn () => x
  fun (ma >>= g) () = let a = ma ()
                      in g a ()
  executeIo ma = ma ()
end

3
我将把实现IO的问题留给其他更了解的人。 (虽然我会指出,我相信他们也会这样做,真正的问题不是“Haskell中如何实现IO?”而是“GHC中如何实现IO?”或“Hugs中如何实现IO?”,等等。我想这些实现差异很大。)然而,这个问题:“如何从另一种语言调用Haskell函数(IO),在这种情况下,我是否需要自己维护IO?”在 FFI规范中有详细解答。

0

注意:我对Clean的经验很少 - 请自行注意!

基于System.IO,使用F. Warren Burton描述的方法变体

  • definition module System.Alt.IO
    
    from Control.Applicative import class pure, class <*>, class Applicative
    from Data.Functor import class Functor
    from Control.Monad import class Monad
    from StdOverloaded import class toString
    from System._OI import OI
    
    :: IO a = IO .(*OI -> a)
    
    execIO :: !(IO a) !*World -> *World
    
    evalIO :: !(IO a) !*World -> *(a, !*World)
    
    withOI :: (*OI -> .a) -> IO .a
    
    putStr :: String -> IO ()
    
    putStrLn :: String -> IO ()
    
    print :: a -> IO () | toString a
    
    getChar :: IO Char
    
    getLine :: IO String
    
    readFileM :: !String -> IO String
    
    writeFileM :: !String !String -> IO ()
    
    instance Functor IO
    instance pure IO
    instance <*> IO
    instance Monad IO
    
    unsafePerformIO :: !(*OI -> .a) -> .a
    unsafePerformIOTrue :: !(*OI -> a) -> Bool
    
  • implementation module System.Alt.IO
    import StdFile from StdFunc import o, id import StdMisc import StdString
    import System._OI import Control.Applicative import Control.Monad import Data.Functor from Text import class Text (trim), instance Text String
    execIO :: !(IO a) !*World -> *World execIO (IO g) world # (u, world) = newOI world #! x = g u = world
    evalIO :: !(IO a) !*World -> *(a, !*World) evalIO (IO g) world # (u, world) = newOI world #! x = g u = (x, world)
    withWorld :: (*World -> *(.a, *World)) -> IO .a withWorld f = IO g where g u # (x, world) = f (getWorld u) = from_world "withWorld" x world
    instance Functor IO where fmap f x = x >>= (lift o f)
    instance pure IO where pure x = IO (\u -> case partOI u of (_, _) = x)
    instance <*> IO where (<*>) f g = liftA2 id f g
    instance Monad IO where bind ma a2mb = IO (run ma) where run (IO g) u # (u1, u2) = partOI u #! x = g u1 # (IO k) = a2mb x = k u2 putStr :: String -> IO () putStr str = withWorld f where f world # (out, world) = stdio world # out = fwrites str out # (_, world) = fclose out world = ((), world) putStrLn :: String -> IO () putStrLn str = putStr (str +++ "\n") print :: a -> IO () | toString a print x = putStrLn (toString x)
    getChar :: IO Char getChar = withWorld f where f world # (input, world) = stdio world # (ok, c, input) = freadc input # (_, world) = fclose input world = (c, world)
    getLine :: IO String getLine = withWorld f where f world # (input, world) = stdio world # (str, input) = freadline input # (_, world) = fclose input world = (trim str, world)
    readFileM :: !String -> IO String readFileM name = withWorld f where f world # (ok, file, world) = fopen name FReadText world # (str, file) = freads file 16777216 # (ok, world) = fclose file world = (str, world)
    writeFileM :: !String !String -> IO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接