【问题标题】:Using fsharp-typeclasses to make a function that works on arbitrary monads使用 fsharp-typeclasses 创建一个适用于任意 monad 的函数
【发布时间】:2013-07-19 11:04:28
【问题描述】:

我正在尝试从论文A pattern for almost compositional functions 中实现composM,它接受一个任意单子并对其进行处理。在 Haskell 中,代码是:

data Expr =
    | Var String
    | Abs String Expr

composExprM :: (Monad m) => (Expr -> m Expr) -> Expr -> m Expr
composExprM f e =
    case e of
        Abs n e -> f e >>= (\e' -> return $ Abs n e')
        _       -> return e

我尝试使用fsharp-typeclasses 和下面的代码:

type Expr =
    | Var of string
    | Abs of string * Expr

let rec composExprM f e = match e with
    | Abs (n, e) -> f e >>= (fun e' -> return' <| Abs (n, e'))
    | Var _      -> return' e

但我得到类型推断错误:

> Could not resolve the ambiguity inherent in the use of the operator 'instance' at or near this program point. Consider using type annotations to resolve the ambiguity.

> Type constraint mismatch when applying the default type 'obj' for a type inference variable. No overloads match for method 'instance'. The available overloads are shown below (or in the Error List window). Consider adding further type constraints

> Possible overload: 'static member Return.instance : _Monad:Return * Maybe<'a> -> ('a -> Maybe<'a>)'. Type constraint mismatch. The type 
      obj    
  is not compatible with type
    Maybe<'a>    
  The type 'obj' is not compatible with the type 'Maybe<'a>'.

> etc.....

我试图通过 fsharp-typeclasses 实现的目标是什么?还是我必须将函数限制为仅使用特定的 monad?

【问题讨论】:

  • 是的,你是对的。修复它(我认为)。

标签: haskell f# monads typeclass fsharp-typeclasses


【解决方案1】:

请记住,使用这种技术的多态函数应该是内联的,这就是“魔法”所在。

所以,只需在let rec 之后添加inline 关键字,它就会编译。

如果函数按预期运行,请告诉我。我稍后会看看那篇论文。

在示例中,您会发现许多定义为与任何 Monad 一起使用的函数。 这是我开始这个项目的主要动机。

【讨论】:

  • 太棒了,成功了!感谢您顺便制作这个项目:)
  • 您可能必须删除 rec 才能使 inline 工作 - 内联递归函数不可能工作。
  • @John:你说得对,反正没必要递归。
  • @John - 你是对的,但请注意,如有必要,您可以执行类似let inline f x = let rec f' x' = ... f' ... in f' x 的操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
  • 1970-01-01
  • 2021-07-08
  • 1970-01-01
相关资源
最近更新 更多