2015-10-27 61 views
3

在F#我試圖得到列表的最後一個元素。我寫了下面的代碼F#代碼有什麼錯誤?

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

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

但是,當我試圖在F#互動來執行它,它抱怨如下

錯誤FS0001:此表達預計將有 int類型,但這裏的類型爲 「一*'b *'c *'d *'e

我只是想知道上面的代碼中出了什麼問題。我知道有不同的智能和優雅的方式來從F#列表中獲取最後一個元素。但我有興趣知道上面代碼中的錯誤嗎?

+5

列表元素用';'不是','分隔。使用'findLast [1; 2; 3; 4; 5]'或者只是'findLast [1..5]' – Lee

+0

這裏您可以找到每個F#程序員遇到的常見錯誤列表:http://fsharpforfunandprofit.com/troubleshooting-fsharp /提示「使用分號列表分隔符」也被提及。 – Olaf

回答

2

1,2,3,4,5是一個元組。 'a * 'b * 'c * 'd * 'e是一個元組定義。用分號創建一個列表[1;2;3;4;5][1,2,3,4,5]是一個元素列表,其中一個元素是五元組。

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

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

感謝您的回答 – sharnol

1

試試這個:

let rec lastElem = function 
    | [] -> None 
    | [x] -> Some x 
    | x::xs -> lastElem xs 

,您可以嘗試在REPL:

> lastElem [1;2;3];; 

val it : int option = Some 3 

> lastElem ["a";"b";"c"];; 

val it : string option = Some "c" 
+0

雖然代碼是正確的,但它不能解釋爲什麼OP代碼是錯誤的;主要是因爲在你的代碼中他的測試會起作用(不會與他預期的結果一樣)返回他列表中唯一的元組項目 – Sehnsucht

+0

謝謝大家! – sharnol

1

正如@菲利普 - 斯科特 - 吉文斯指出,你可能已經做了一個完全常見(特別是C#的ERS),錯誤和使用逗號,而不是單獨一個分號的列表。

這會導致元組列表[(1,2,3,4,5)]而不是整數列表[1; 2; 3; 4; 5]。獲得意想不到的星號在你的類型定義是這樣的症狀:)

也就是說,這裏的幾個不同的功能,從你的元組,列表獲取最後一個值,元組列表(參考:https://stackoverflow.com/a/1175123/5470873):

// Data: 
let tuples = [ (1,2,3,4,5); ]  // = [1,2,3,4,5] 
let firstListElement = tuples.[0] 


// Access: 
let rec lastItemInList = function 
    | hd :: [] -> hd 
    | hd :: tl -> lastItemInList tl 
    | _ -> failwith "Empty list." 
let lastValueOfFirstItem = function 
    | (_, _, _, _, last) :: _ -> last 
    | _ -> -1 
let lastValueOfTuple = function _, _, _, _, last -> last 
// same as: let lastValueOfTuple myTuple = 
//    match myTuple with 
//    | (_, _, _, _, last) -> last 


// Examples: 
tuples |> lastItemInList    // val it : int * int * int * int * int = (1, 2, 3, 4, 5) 
tuples |> lastValueOfFirstItem  // val it : int = 5 
tuples |> List.map lastValueOfTuple // val it : int list = [5] 
firstListElement |> lastValueOfTuple // val it : int = 5 
+0

感謝您分享上面的鏈接。 – sharnol