空列表中的 F# 值限制 [英] F# value restriction in empty list
问题描述
我有一个 F# 函数:
I have a F# function:
let removeEven (listToGoUnder : _ list) =
let rec listRec list x =
match list with
| [] -> []
| head::tail when (x%2 = 0) -> head :: listRec (tail) (x+1)
| head::tail -> listRec (tail) (x+1)
listRec listToGoUnder 0
它删除列表中偶数索引处的所有元素.如果我给列表一些输入,它会起作用,比如 removeEven ['1';'2';'3']
我得到 ['1';'3']
我应该这样做.但是当我插入一个空列表作为参数时,我得到这个错误:
It removes all elements at an even index in a list.
It works if I give the list some imput, like removeEven ['1';'2';'3']
I get ['1';'3']
which I am supposed to. But when I insert a empty list as parameter, I get this error:
stdin(78,1):错误 FS0030:值限制.它"的价值是推断具有泛型类型
stdin(78,1): error FS0030: Value restriction. The value 'it' has been inferred to have generic type
val it : '_a list 或者将 'it' 定义为一个简单的数据项,使它是一个带有显式参数的函数,或者,如果您不打算使用它要通用,请添加类型注释.
val it : '_a list Either define 'it' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation.
有人帮忙吗?
推荐答案
空列表([]
)比较特殊;它可以是任何类型的列表.因此,编译器会抱怨您没有 []
的特定类型.在参数上添加类型注释有助于解决问题:
The empty list ([]
) is quite special; it can be a list of any type. Therefore, the compiler complains that you don't have a specific type for []
. Adding type annotation on the argument helps to solve the problem:
let results = removeEven ([]: int list)
或@kvb 建议的更多惯用类型注释:
let results: int list = removeEven []
这可能超出问题范围,但您的函数应该命名为 removeOdd
,因为索引通常从 0
开始,并且您的函数会删除所有具有奇数索引的元素.此外,如果您在列表的前两个元素上使用模式匹配,而不是保留一个计数器 x
来检查索引,事情会更加清楚:
This is probably beyond the question, but your function should be named as removeOdd
since indices often start from 0
and your function removes all elements with odd indices. Moreover, things are much more clear if you use pattern matching on first two elements of the list rather than keep a counter x
for checking indices:
let rec removeOdd = function
| [] -> []
| [x] -> [x]
| x::_::xs -> x::removeOdd xs
这篇关于空列表中的 F# 值限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!