如何在Java中实现Haskell的IO类型?

Kyl*_*ean 5 java haskell

这是我的第一次尝试:

import java.util.function.*;
import java.util.ArrayList;
public class IO<A> {
    private Function<World,Tuple<World,A>> transform;
    private class World {
        private ArrayList<String> stdin;
        private ArrayList<String> stdout;
        public World() {
            this.stdin  = new ArrayList<String>();
            this.stdout = new ArrayList<String>();
        }
    }
    private class Tuple<F,S> {
        public F fst;
        public S snd;
        public Tuple(F fst, S snd) {
            this.fst = fst;
            this.snd = snd;
        }
    }
    public IO(Function<World,Tuple<World,A>> transform) {
        this.transform = transform;
    }
    public IO<A> pure(A a) {
        return new IO<A>(r -> new Tuple<World,A>(r,a));
    }
    public <B> IO<B> bind(IO<A> io, Function<A,IO<B>> f) {
        return new IO<B>(r -> {
            Tuple<World,A> result = io.transform.apply(r);
            IO<B> ioB = f.apply(result.snd);
            return ioB.transform.apply(result.fst);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试编译它时,我收到以下错误:

IO.java:29: error: incompatible types: IO<B>.World cannot be converted to IO<A>.World
            Tuple<World,A> result = io.transform.apply(r);
                                                        ^
  where B,A are type-variables:
    B extends Object declared in method <B>bind(IO<A>,Function<A,IO<B>>)
    A extends Object declared in class IO
Run Code Online (Sandbox Code Playgroud)

我不明白的是世界级与类型变量没有关系,但javac认为它确实存在.我究竟做错了什么?

dfe*_*uer 2

我认为“操作单子”方法更适合解释 Haskell I/O 的本质。Haskell 版本可以非常简单:

data PrimOp a where
  PutStr :: String -> PrimOp ()
  GetLine :: PrimOp String
  -- Whatever other primitives you want

data MyIO a where
  Pure :: a -> MyIO a
  Bind :: !(MyIO a) -> (a -> MyIO b) -> MyIO b
  LiftPrim :: !(PrimOp a) -> MyIO a

instance Functor MyIO where
  fmap = liftM

instance Applicative MyIO where
  pure = Pure
  (<*>) = ap

instance Monad MyIO where
  (>>=) = Bind
Run Code Online (Sandbox Code Playgroud)

这些MyIO值并不是一些神奇的世界传递函数;而是它们的一部分。它们只是简单的数据。如果我们愿意,我们可以解释数据以实际执行所表示的操作:

runPrimOp :: PrimOp a -> IO a
runPrimOp (PutStr s) = putStr s
runPrimOp GetLine = getLine

runMyIO :: MyIO a -> IO a
runMyIO (Pure a) = pure a
runMyIO (Bind m f) = runMyIO m >>= runMyIO . f
runMyIO (LiftPrim prim) = runPrimOp prim
Run Code Online (Sandbox Code Playgroud)

实际上可以编写一个 Haskell 编译器,其IO类型看起来很像MyIO,并且其运行时系统直接解释该类型的值。


我尝试将下面的内容翻译成Java。我从来都不是一名真正的 Java 程序员,而且我已经很长时间没有使用它了,所以这可能非常不惯用,甚至是错误的。我想您可能希望使用某种版本的“访问者模式”来表示Bind和的解释Pure(将事物带入诸如 之类的通用领域Control.Monad.Operational),同时使用的子类的run方法。由于我不太了解正确的 Java 方法,因此我尝试保持简单。PrimOpIO

public interface IO <A> {
  public A run ();
}

public final class Pure <A> implements IO <A> {
  private final A val;
  Pure (A x) { val = x; }
  public A run () {
      return val;
      }
}
Run Code Online (Sandbox Code Playgroud)

棘手的一点是Bind,它需要存在量化。我不知道在 Java 中执行此操作的惯用方法,所以我做了一些似乎有效的尴尬的事情。也就是说,我编写了一个OpenBind公开两个类型变量的辅助类,然后Bind编写了一个OpenBind包装其中一个变量的类。

import java.util.function.Function;

public final class Bind <A> implements IO <A> {
    private final OpenBind <?,A> ob;

    public <B> Bind (IO <B> m, Function <B,IO <A>> f) {
        ob = new OpenBind <B,A> (m, f);
    }

    public A run() {
        return (ob.run());
    }

    private final static class OpenBind <Fst,Snd> {
        private final IO <Fst> start;
        private final Function <Fst, IO <Snd>> cont;
        public OpenBind (IO <Fst> m, Function <Fst, IO <Snd>> f) {
            start = m;
            cont = f;
        }
        public final Snd run () {
            Fst x = start.run();
            IO <Snd> c = cont.apply(x);
            return (c.run());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

primops 本身非常简单(我找不到 Java 的等价物,()所以我写了自己的Unit):

public class PutStr implements IO <Unit> {
  private String str;
  public PutStr (String s) {
      str = s;
  }
  public Unit run () {
      System.out.print(str);
      return Unit.unit;
  }
}

public final class Unit {
  private Unit () {}
  public static final Unit unit = new Unit ();
}

public class GetLine implements IO <String> {
    private GetLine () {}
    public static final GetLine getLine = new GetLine ();
    public String run () {
      // Replace the next line with whatever you actually use to
      // read a string.
      return "";
  }
}
Run Code Online (Sandbox Code Playgroud)