榆树分拣和[比较]

joh*_*ual 3 sorting list elm

我对Elm进行排序时使用了什么排序算法List

> sort [1,3,5,6]
[1,3,5,6] : [comparable]
Run Code Online (Sandbox Code Playgroud)

什么[comparable]类型以及如何找回number

> [1,2]:: (sort [3,2,1])
[1 of 1] Compiling Repl                ( repl-temp-000.elm )
Type error on line 4, column 3 to 24:
        [1,2] :: (sort [3,2,1])

   Expected Type: [number]
     Actual Type: comparable
Run Code Online (Sandbox Code Playgroud)

这可能是了解List榆树如何实施的好时机,但我现在不想过于深入.只是让它运行起来.

Joe*_*Joe 8

Sort将列表转换为javascript数组,然后对其进行排序,然后将结果转换回elm列表.这意味着排序本身就是浏览器使用的任何实现(绝对是订单大小*日志(大小)算法).

在elm中排序的来源:https://github.com/elm-lang/Elm/blob/20ccc834c1a597d1ef356c14073670b62f90d875/libraries/Native/List.js#L267-L269

comparable类型是有趣的,但不包括数字.你的代码的问题是你正在使用(::)(发音为cons)而不是(++)发音附加.你想做:

sorted = [1,2] ++ (sort [6,5,4,3])
Run Code Online (Sandbox Code Playgroud)

示例:http://share-elm.com/sprout/53dd978ce4b07afa6f983b7d

希望这可以帮助!