我不明白下面的代码有什么问题:
let toClass (problem:Problem<'a>) (classID:int) (items:'a list) =
let newFreqTable = (problem.FreqTables.[classID]).count items
{ problem with FreqTables = newFreqTable :: (problem.FreqTables |> List.filter (fun i -> i.ClassID <> classID)) }
type Problem<'a> when 'a : equality with member this.toClass (classID:int) (items:list<'a>) = toClass this classID items
我有一个Problem
类型,不过是一种将任意数量的分组的方法FreqTables
-“频率表”的简称。因此,toClass
方法只需要使用适当的freqTable(通过classID
参数)并返回一个新的-具有计算的给定项。
let typeIndependentCall = toClass p 0 ["word"; "word"; "s"] // this works perfectly
let typeDependentCall = typeIndependentCall.toClass 1 ["word"; "s"]
// gives an error: "One or more of the overloads of this method has
// curried arguments. Consider redesigning these members to take
// arguments in tupled form".
我对F#和函数式编程非常陌生。将行为附加到我的类型上的正确方法是什么?
在F#中,有两种将参数传递给函数的主要方法:curried和tupled。咖喱形式是您在上面的代码中使用的形式,它具有一些关键的好处,首先是部分应用程序。
例如,而不是思考
fun add a b = a + b
作为一个接受2个参数并返回值的函数,我们可以将其视为一个参数的函数,该参数返回一个具有一个参数的函数。这就是为什么我们的函数的类型签名是
Int -> Int -> Int
或者,更清楚地说,
Int -> (Int -> Int)
但是,当重载方法时,我们只能使用元组参数形式
(Int, Int) -> Int
这样做的原因是优化,讨论在这里
要使代码正常工作,请使用
type Problem<'a> when 'a : equality with member this.toClass (classID:int, items:list<'a>) = toClass this classID items
并这样称呼它:
let typeDependentCall = typeIndependentCall.toClass(1, ["word"; "s"])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句