List comprehension vs high-order functions in F#

后端 未结 3 535
伪装坚强ぢ
伪装坚强ぢ 2021-02-09 02:22

I come from SML background and feel quite comfortable with high-order functions. But I don\'t really get the idea of list comprehension. Is there any situation where list co

3条回答
  •  猫巷女王i
    2021-02-09 03:24

    Adding to Tomas Petricek's answer. You can make the list version tail recursive.

    let nums3 n =
        let rec nums3internal acc n = 
            if n = 100000 then
                acc
            else
                nums3internal (n::acc) (n+1) //Tail Call Optimization possible
    
        nums3internal [] n |> List.rev
    
    nums3 0
    

    With the added benefit of a considerable speedup. At least when I measured with the stopwatch tool I get. (nums2 being the algorithm using Seq).

    Nums2 takes 81.225500ms
    Nums3 takes 4.948700ms
    

    For higher numbers this advantage shrinks, because List.rev is inefficient. E.g. for 10000000 I get:

    Nums2 takes 11054.023900ms
    Nums3 takes 8256.693100ms
    

提交回复
热议问题