F# 初學編程小習題

1、計算一個列表中的正數個數

let countPositive = fun (input : int list) ->
    // add logic here, and leave the result as last line

let runTest = fun (input : int list) ->
    printfn "input = %A" input
    printfn "output = %d" <| countPositive input

runTest <| [1; 2; 3; 4; 5; 0; -1; 20; -2; 30]

答案:

let countPositive = fun (input : int list) ->
    input
    |> List.filter (fun x -> x > 0) 
    |> (fun x -> x.Length) 

let runTest = fun (input : int list) ->
    printfn "input = %A" input
    printfn "output = %d" <| countPositive input 
    
runTest  [1; 2; 3; 4; 5; 0; -1; 20; -2; 30]

2、檢查列表是否爲迴文列表,迴文列表表示從兩端讀取列表時列表是相同的,例如 let palindrome = [1, 2, 3, 2, 1]

let isPalindrome = fun (input : int list) ->
	// add logic here, and leave the result as last line

let runTest = fun (input : int list) ->
	    printfn "input = %A" input
    printfn "output = %A" <| isPalindrome input

runTest <| [1, 2, 3, 4, 5, 0, -1, 20, -2, 30]
runTest <| [1; 2; 3; 4; 5; 5; 4; 3; 2; 1]

答案:

let isPalindrome = fun (input : int list) ->
    input
    |>List.fold (fun acc elem -> elem::acc) []
    |>List.forall2 (fun elem1 elem2 -> elem1 = elem2) input

=================================第二種==========================================

let isPalindrome = fun (input : int list) ->
    let mutable result = true
    let mutable i = 0
    while (i <= (input.Length-1)/2) && result do
        if input.Item(i) <> input.Item(input.Length-1-i) then result <- false 
        i <- i + 1
    result

3、找出一個非空列表中出現最多次數的元素

let countMostCommon = fun (input : int list) ->
    input 
    |> List.countBy id 
    |> List.maxBy snd
    |> fst
    
let runTest = fun (input : int list) ->
    printfn "input = %A" input
    printfn "output = %A" <| countMostCommon input
    
runTest <| [1; 2; 3; 3]

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章