Created
June 7, 2015 12:05
-
-
Save alskipp/7308e40b00243a83d873 to your computer and use it in GitHub Desktop.
Haskell example of spreadsheet-like column sorting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
-} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by sketchyTech’s Swift blog post which tackles the same problem using Swift.