Skip to content

Instantly share code, notes, and snippets.

@namlook
Created June 29, 2016 08:27
Show Gist options
  • Save namlook/bc77a1cf7f8d0d044a5fe30bad25e1cb to your computer and use it in GitHub Desktop.
Save namlook/bc77a1cf7f8d0d044a5fe30bad25e1cb to your computer and use it in GitHub Desktop.
Dynamically sort by field in Elm
import Dict
import List
import Html exposing (text)
type alias Expense =
{ title : String
, amount: Float
}
expenses = [{title = "bbb", amount = 3}, {title = "aaa", amount = 5}]
compareBy accessor a b = compare (accessor a) (accessor b)
expensesAccessors =
Dict.fromList [ ( "title", compareBy .title ), ( "amount", compareBy .amount ) ]
sortByField : String -> Dict.Dict String (a -> a -> Order) -> List a -> List a
sortByField fieldname accessors list =
case Dict.get fieldname accessors of
Just fn ->
List.sortWith fn list
Nothing ->
list
sortedExpenses = sortByField "title" expensesAccessors expenses
main =
text <| toString sortedExpenses
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment