gpt4 book ai didi

generics - 使用泛型的计算表达式

转载 作者:行者123 更新时间:2023-12-03 06:28:42 24 4
gpt4 key购买 nike

我正在努力解决这个通用表达式的问题:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com