2
votes

Total newbie to F# here, need some help. So the question says to write a function

downTo : int -> int list

so that downTo n returns the n-element list [n; n-1; ...;1] using if-then-else and then pattern matching.

So this is what I've tried for the if-then-else portion

let rec downTo n : int -> int list  =
    let list = []

    if n > 1 then 
        n :: list
        downTo (n - 1)
    else
        list 

so I'm getting a warning at n :: list that says 'This expression should have type 'unit' but has type 'int list'. Use ignore to discard the result etc.

and an error on the last line 'This expression is supposed to have type int -> int list but here has type 'a list'

I need some guidance. First question, in the declaration of the function, should it be the way it is, with n : int -> int list? Should I remove the n so that it reads

downTo : int -> int list

like in the problem statement? I've been trying to research for days and haven't seen a declaration like this anywhere. I'm very confused. Thank you for your help in advance.

1

1 Answers

4
votes

I think you have misunderstood what list is. Also you don't need annotations.

A simple version

let rec downto n =
    if n > 0 then n :: ( downto n-1) else []