空列表中的F#值限制 [英] F# value restriction in empty list

查看:80
本文介绍了空列表中的F#值限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个F#函数:

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'],它将起作用.但是当我插入一个空列表作为参数时,出现此错误:

stdin(78,1):错误FS0030:值限制. "it"的值一直是 推断具有通用类型

val it:'_a list要么将'it'定义为一个简单的数据术语, 它是带有显式参数的函数,或者,如果您不打算使用它, 要通用,请添加类型注释.

有帮助吗?

解决方案

空列表([])非常特殊;它可以是任何类型的列表.因此,编译器会抱怨您没有[]的特定类型.在参数上添加类型批注有助于解决问题:

let results = removeEven ([]: int list)

或@kvb建议的更多惯用类型注释:

let results: int list = removeEven []

这可能超出了问题的范围,但是您的函数应命名为removeOdd,因为索引通常从0开始,并且您的函数会删除所有具有奇数索引的元素.此外,如果在列表的前两个元素上使用模式匹配,而不是使用计数器x来检查索引,则事情会更加清楚:

let rec removeOdd = function
    | [] -> []
    | [x] -> [x]
    | x::_::xs -> x::removeOdd xs

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

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): error FS0030: Value restriction. The value 'it' has been inferred to have generic type

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.

Help, anybody?

解决方案

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)

or more idiomatic type annotation as suggested by @kvb:

let results: int list = removeEven []

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆