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]