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]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值