- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在努力解决这个通用表达式的问题:
type World<'a, 'b, 'c> = World of 'a * 'b * 'c
type StateFunc<'State, 'T> = 'State -> 'T * 'State
type StateMonadBuilder<'State>() =
// M<'T> -> M<'T>
member b.ReturnFrom a : StateFunc<'State, 'T> = a
// 'T -> M<'T>
member b.Return a : StateFunc<'State, 'T> = ( fun s -> a, s)
// M<'T> * ('T -> M<'U>) -> M<'U>
member b.Bind(p : StateFunc<_, 'T>, rest : 'T -> StateFunc<_,_>) : StateFunc<'State, 'U> =
(fun s ->
let a, s' = p s
rest a s')
// Getter for the whole state, this type signature is because it passes along the state & returns the state
member b.get : StateFunc<'State, _> = (fun s -> s, s)
// Setter for the state
member b.put (s:'State) : StateFunc<'State, _> = (fun _ -> (), s)
let state = StateMonadBuilder<World<'a, 'b, 'c>> ()
let set1 a = state {
let! World(_, b, c) = state.get
do! state.put(World(a, b, c)) }
let set2 b = state {
let! World(a, _, c) = state.get
do! state.put(World(a, b, c))}
let testfun<'a, 'b> (one:'a) (two:'b) : StateFunc<World<'a, 'b, _>, _> = state {
let! World(a,b,c) = state.get
do printfn "%A" a
do printfn "%A" b
do printfn "%A" c
do printfn "%A" "---------------------------"
do! set1 one
do! set2 two
let! World(a,b,c) = state.get
do printfn "%A" a
do printfn "%A" b
do printfn "%A" c
do! state.put(World(a, b, c)) }
let appliedTest = testfun<int,int> 10 20
let result = appliedTest (World<int, int, int>(10, 20, 30))
目标是拥有一个通用的状态单子(monad)来发扬World
,一个三元组。编译器报告错误 testfun<'a, 'b> (one:'a) (two:'b)
error FS0670: This code is not sufficiently generic. The type variable 'a could not be generalized because it would escape its scope.
此外,World<int, int, int>(10, 20, 30)
声称类型参数是意外的,这让我感到惊讶。
我认为问题实际上出在 let state = StateMonadBuilder<World<'a, 'b, 'c>> ()
上,换句话说,我不应该用泛型初始化状态构建器。
谢谢!
编辑我认为我想做的事情是由于缺乏更高种类的类型而被阻止的:http://cs.hubfs.net/topic/None/59392
最佳答案
问题不在于缺乏更高级的种类,而在于 value restriction :你不能定义state
作为 StateMonadBuilder<World<'a,'b,'c'>>
类型的通用值。自 state
是纯粹的,一行修复是使 state
一个type function相反:
let state<'a,'b,'c> = StateMonadBuilder<World<'a, 'b, 'c>> ()
关于World<int,int,int>(10,20,30)
的问题- 类型 World
可以采用通用参数,但联合案例不能。由于类型完全由构造函数的参数确定,因此如果您删除参数,则会推断出类型,但如果您想确定,也可以添加类型注释: (World(10,20,30) : World<int,int,int>)
关于generics - 使用泛型的计算表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20194599/
我是一名优秀的程序员,十分优秀!