2017-10-19 132 views
2

我想表达F#自由单体的教会编码。 Free是专门针对特定仿函数的,Effect教会在F编码自由单体#

我可以写出return_ : 'T -> Free<'T>bind: ('T -> Free<'U>) -> Free<'T> -> Free<'U>没有任何问题。

我的实施草图如下。

type Effect<'T> 
    = GetStr of (string -> 'T) 
    | PutStr of string * 'T 


module Effect = 

    let map (f: 'a -> 'b) : Effect<'a> -> Effect<'b> = function 
     | GetStr k -> 
      GetStr(f << k) 

     | PutStr (s,t) -> 
      PutStr(s, f t) 


type Free<'T> = 
    abstract Apply : ('T -> 'R) -> (Effect<'R> -> 'R) -> 'R 

module Free = 
    let inline runFree (f:Free<'T>) (kp: 'T -> 'R) (kf: Effect<'R> -> 'R) : 'R = 
     f.Apply kp kf 

    let return_ (x: 'a) : Free<'a> = 
     { new Free<'a> 
      with 
       member __.Apply kp _ = 
        kp x 
     } 

    let bind (f: 'a -> Free<'b>) (m: Free<'a>) : Free<'b> = 
     { new Free<'b> 
      with 
       member __.Apply kp kf = 
        runFree m 
         (fun a -> 
          runFree (f a) kp kf 
         ) 
         kf 
     } 

当我尝试写这个编码的解释,我打了一个问题。

考虑下面的代码:

module Interpret = 

    let interpretEffect = function 
     | GetStr k -> 
      let s = System.Console.ReadLine()    
      (k s , String.length s) 

     | PutStr(s,t) -> 
      do System.Console.WriteLine s 
      (t , 0) 

    let rec interpret (f: Free<string * int>) = 
     Free.runFree 
      f 
      (fun (str,len) -> (str,len)) 
      (fun (a: Effect<Free<string*int>>) -> 
       let (b,n) = interpretEffect a 
       let (c,n') = interpret b 
       (c, n + n') 
      ) 

我得到的第三个参数类型错误Free.runFreeinterpret函数中:

... 

(fun (a: Effect<Free<string*int>>) -> 
     ^^^^^^^^^^^^^^^^^^ ------ Expecting a Effect<string * int> but given a Effect<Free<string*int>> 

我明白为什么会这样(的结果类型第一个函数确定'R === string*int)并怀疑可以使用rank-2函数(可以用F#编码,例如http://eiriktsarpalis.github.io/typeshape/#/33)解决,但我不知道如何应用它。

任何指针将不胜感激。

迈克尔

+0

您可以查看您的代码示例吗? “Apply”的第二个参数不会输入检查。 – scrwtp

+0

@scrwtp,谢谢,现在修复。 –

回答

1

你不需要做任何事情有,编译建议类型实际上是正确的(在与runFree型线)。

看来,你在想什么的还有斯科特编码(从this Haskell question撕开):

runFree :: Functor f => (a -> r) -> (f (F f a) -> r) -> F f a -> r 

其中F f a将是你Effect -specialised Free<'a>f (F f a)Effect<Free<'a>>,这就是你正在尝试使用。

而教会编码是:

runFree :: Functor f => (a -> r) -> (f r -> r) -> F f a -> r 

其中f rEffect<'a> - 从而使其更容易在F#快递(这就是为什么我假设你在第一时间使用它

。这是我有什么interpret

let rec interpret (f: Free<string * int>) = 
    Free.runFree 
     f 
     (fun (str,len) -> (str,len)) 
     (fun (a: Effect<_>) -> 
      let (b,n) = interpretEffect a 
      let (c,n') = interpret (Free.pureF b) 
      (c, n + n') 
     ) 

其中pureF

let pureF (x: 'a) : Free<'a> = 
    { new Free<'a> with member __.Apply kp _ = kp x } 

即您的return_函数。

我认为定义相应的freeF函数会清除一些事情(例如为什么Effect<'a>是一个仿函数 - 在粘贴的代码中没有使用这个事实)。