Skip to content

Instantly share code, notes, and snippets.

@alskipp
Created June 7, 2015 12:05
Show Gist options
  • Select an option

  • Save alskipp/7308e40b00243a83d873 to your computer and use it in GitHub Desktop.

Select an option

Save alskipp/7308e40b00243a83d873 to your computer and use it in GitHub Desktop.

Revisions

  1. alskipp created this gist Jun 7, 2015.
    31 changes: 31 additions & 0 deletions table_sort.hs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    import Data.List
    import Data.Ord

    data Field = Str String
    | Num Double
    deriving (Show, Eq, Ord)

    data Column = Column { fields::[Field] }
    deriving (Show, Eq, Ord)

    data Table = Table { columns::[Column] }
    deriving (Show, Eq, Ord)

    sortTableByColumn :: Table -> Int -> Table
    sortTableByColumn t i = tableFromRows $ sortRows
    where sortRows = sortBy (comparing (!! clip i)) $ rows
    clip = max 0 . min ((length . columns $ t) - 1) -- prevent out of bounds index
    rows = transpose . fmap fields . columns $ t
    tableFromRows = Table . fmap Column . transpose


    column1 = Column [Num 8, Str "pear", Str "apple", Str "shoes", Num 10]
    column2 = Column [Num 8, Num 12, Str "apple", Str "pair", Num 10]
    column3 = Column [Num 15, Num 1, Str "zebra", Str "bear", Num 12]

    table = Table [column1, column2, column3]

    {- examples:
    sortTableByColumn table 0
    sortTableByColumn table 2
    -}