在Haskell中,我们可以编写如下代码:
// (<*>) :: Applicative f => f (a -> b) -> f a -> f b
// const :: a -> b -> a
// id :: b -> b
let id = const <*> const
如何在F#中做同样的事情?
我尝试编写类似这样的代码,但它并不相同
let ( <*> ) f v =
match v with
| Some v' ->
match f with
| Some f' -> Some (f' v')
| _ -> None
| _ -> None
let cnst a _ = a
let id = cnst <*> cnst // but it seems impossible
let id' x = (Some (cnst x)) <*> (Some(cnst x x)) // it works
但是在Haskell id::b->b
中,在F#id:'a->'a Option
我做错了什么?如何实现相同的结果?
PS:正如我所知道的那样,我们的值被包含在一个上下文中,就像Functors一样,函数也包含在上下文中!
Some((+)3) and Some(2)
在这种情况下,Context是Option
Applay
方法是这样的:
let Apply funInContext valInContext =
match funInContext with // unwrap function
| Some f ->
match valInContext with // unwrap value
| Some v -> Some(f v) // applay function on value and wrap it
| _ -> None
| _ -> None
答案 0 :(得分:9)
我对你的代码试图实现的内容感到有些困惑,因为它的类型为
(a -> Maybe b) -> Maybe a -> Maybe b
这是我们通常赋予Maybe
/ option
的monad结构的绑定类型,但如果您尝试使用我们的函数的应用实例则没有意义在哈斯克尔。我们需要改变两件事,第一件事是我们需要使用函数和 applicatives 才能让代码达到预期的效果。应该有类型
(a -> (b -> c)) -> (a -> b) -> (a -> c)
所以我们可以把它写成
let ( <*> ) f x a = (f a) (x a)
现在,如果我们执行原始示例
(cnst <*> cnst) a = (cnst a) (cnst a)
= a
所以我们的确需要cnst <*> cnst = id
。