Skip to content

Instantly share code, notes, and snippets.

@alskipp
Created June 7, 2015 12:05
Show Gist options
  • Save alskipp/7308e40b00243a83d873 to your computer and use it in GitHub Desktop.
Save alskipp/7308e40b00243a83d873 to your computer and use it in GitHub Desktop.
Haskell example of spreadsheet-like column sorting
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
-}
@alskipp
Copy link
Author

alskipp commented Jun 7, 2015

Inspired by sketchyTech’s Swift blog post which tackles the same problem using Swift.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment