sGlow
sGlow

Reputation: 445

F#: error creating a list of size n

I'm trying to create a list of size n pulling elements from a larger, already created list. I'm getting an error saying: This value is not a function and cannot be applied. Incomplete pattern matches on this expression. For example, the value '[]' may indicate a case not covered by the pattern(s). at 7,16

Can anyone help see what I'm doing wrong? Also, I'm trying to understand F# so I don't really want anything that can do what I'm asking for me, unless it's an FYI kind of thing. But I'd still want help creating a function to do this.

//create a list of size n from beginning of a dataset
let populateList n =
    let starterList = []
    let data = [1;2;3;4;5;6;7;8]
    let rec helper count aList = 
        let head::tail = aList
        if count < k then head :: helper count+1 tail else []


    helper 0 data

populateList 3

Upvotes: 2

Views: 139

Answers (1)

JLRishe
JLRishe

Reputation: 101700

It's failing to run because of this:

head :: helper count+1 tail

Because function invocations have higher operator precedence than the infix + operator, this is being interpreted as:

head :: ((helper count) + (1 tail))

Since 1 is not a function, you are getting an error here.

You can fix this by adding parentheses:

head :: helper (count+1) tail

The "Incomplete pattern matches" warning will not prevent it from running, but it does indicate something that you should address because it can lead to a runtime error.

The correct way to address it is by using pattern matching to cover all the possible patterns:

let rec helper count aList = 
    match aList with
    | head::tail -> if count < n then head :: helper (count+1) tail else []
    | [] -> []

This will ensure that you do not attempt to split an empty list into a head and a tail.

Since this function now returns [] both in the base case and in the case that aList is empty, you can further simplify this by using when and a default match condition:

let rec helper count aList = 
    match aList with
    | head::tail when count < n -> head :: helper (count+1) tail
    | _ -> []

Upvotes: 6

Related Questions