F# value restriction in empty list
Asked Answered
C

1

7

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?

Capstan answered 23/2, 2012 at 12:54 Comment(0)
C
10

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
Celerity answered 23/2, 2012 at 13:6 Comment(2)
Note that you can also add the annotation directly to results instead, which might be more idiomatic.Sunlight
The proposed removeOdd function fails when the argument is []. I'm trying to solve this in a generic way, but I can't manage to handle the [] case without a "error FS0030: Value restriction". Is it possible to make such function truly generic?Assume

© 2022 - 2024 — McMap. All rights reserved.