F# value restriction in empty list

后端 未结 1 1517
悲哀的现实
悲哀的现实 2020-12-20 18:59

I have a F# function:

let removeEven (listToGoUnder : _ list) =
    let rec listRec list x =
        match list with
        | [] -> []
        | head::ta         


        
相关标签:
1条回答
  • 2020-12-20 19:34

    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
    
    0 讨论(0)
提交回复
热议问题