Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong in F# code?

In F# I am trying to get last element of give list. I wrote below code

let rec findLast t =
    match t with
        | hd :: [] -> hd
        | hd :: tl -> findLast tl
        | _ -> -1

printfn "%A" (findLast [1,2,3,4,5])

But when I tried to execute it in F# Interactive it complain as below

error FS0001: This expression was expected to have type int but here has type 'a * 'b * 'c * 'd * 'e

I just want to know what is wrong in above code. I know there are different smart and elegant ways to get last element from list in F#. But I am interested to know what is wrong in above code ?

like image 934
Cloud Spider Avatar asked Jul 03 '26 08:07

Cloud Spider


1 Answers

1,2,3,4,5 is a tuple. 'a * 'b * 'c * 'd * 'e is a tuple definition. Create a list with semicolons [1;2;3;4;5]. [1,2,3,4,5] is a list of tuples with one item which is a quintuple.

let rec findLast t =
    match t with
        | hd :: [] -> hd
        | hd :: tl -> findLast tl
        | _ -> -1

printfn "%A" (findLast [1;2;3;4;5])
like image 80
Phillip Scott Givens Avatar answered Jul 05 '26 22:07

Phillip Scott Givens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!