Get the last list item in f #

I want to get the last element of a list, and my logic is to cancel the list and get its head:

module Program1 = 

    let last list =
        let newList=List.rev list;
        List.head newList;
        newList 

    let mainP1()=
        let list= [ 1; 2; 3] 
        printfn "Ultimul element al listei %A este %A" list (last list )

but he gives me this error

Error       Type mismatch. Expecting a
    unit list    
but given a
    int list    
The type 'unit' does not match the type 'int'   

Can anybody help me?

+4
source share
1 answer

There is a lot of unpacking here.

At first , your function does not return what you want to return. Look at this last line, the one that says newList? That your function returns a value. The last line of the function body is the return value. This way you are returning a list, not the last item.

, List.head, . . . F # : , , - , F # ( ), .

: unit. , unit, . , , (unit " " ), ?

, : , unit. List.head newList unit, newList unit list. list unit list. unit list -> unit list (.. unit list unit list).

int list , unit list, : Expecting a unit list but given a int list.

, ,, , , ! , . - . : , , - . , F #:

let rec last list =
  match list with
  | [x] -> x   // The last element of one-element list is the one element
  | _::tail -> last tail   // The last element of a longer list is the last element of its tail
  | _ -> failwith "Empty list"   // Otherwise fail

, List.last, ( , ).

let mainP1()=
  let list= [ 1; 2; 3] 
  printfn "Ultimul element al listei %A este %A" list (List.last list)

, , - . List.last ( List.head) , , , . , List.tryLast:

let mainP1()=
  let list= [1; 2; 3] 
  match List.tryLast list with
  | Some x -> printfn "Ultimul element al listei %A este %A" list x
  | None -> printfn "Lista %A este goală" list
+5

Source: https://habr.com/ru/post/1657221/


All Articles