Skip to content

Instantly share code, notes, and snippets.

@ivanbrennan
Created April 22, 2018 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivanbrennan/e88d62512e4539c874c6b78fd281dbc8 to your computer and use it in GitHub Desktop.
Save ivanbrennan/e88d62512e4539c874c6b78fd281dbc8 to your computer and use it in GitHub Desktop.
Folds
import Data.Maybe
import qualified Data.Map as Map
type Cell = Map.Map String Int
cell :: [(String, Int)] -> Cell
cell = Map.fromList
isOn :: Cell -> Bool
isOn = (> 0) . Map.findWithDefault 0 "on"
count :: Cell -> Int
count = Map.findWithDefault 1 "count"
combine :: Cell -> Cell -> Cell
combine x y = Map.alter g "count" x
where
g :: Maybe Int -> Maybe Int
g = Just . (+ count y) . fromMaybe 1
agg :: Cell -> [Cell] -> [Cell]
agg x [] = x : []
agg x (y:ys)
| isOn x && isOn y = combine x y : ys
| otherwise = x : y : ys
testCells :: [Cell]
testCells = map cell [ [("day", 1)]
, [("day", 2), ("on", 1)]
, [("day", 3), ("on", 1)]
, [("day", 4)]
, [("day", 5), ("on", 1)]
, [("day", 6), ("on", 1)]
, [("day", 7), ("on", 1)] ]
testResult :: [Cell]
testResult = foldr agg [] testCells
-- [ fromList [("day",1)]
-- , fromList [("day",2), ("on",1), ("count",2)]
-- , fromList [("day",4)]
-- , fromList [("day",5), ("on",1), ("count",3)] ]
function foldr(xs) {
if (xs.length == 0) {
return [];
} else {
const tail = foldr(xs.slice(1))
return agg(xs[0], tail);
}
}
function agg(head, tail) {
if (tail.length == 0) {
return [head];
} else if (head['on'] && tail[0]['on']) {
return [combine(head, tail[0])].concat(tail.slice(1));
} else {
return [head].concat(tail);
}
}
function combine(a, b) {
const n = b['count'] || 1;
return Object.assign({ count: n + 1 }, Object.assign({}, a));
}
const testCells = [
{ day: 1 },
{ day: 2, on: 1 },
{ day: 3, on: 1 },
{ day: 4 },
{ day: 5, on: 1 },
{ day: 6, on: 1 },
{ day: 7, on: 1 }
];
const testResult = foldr(testCells);
// [
// { day: 1 },
// { day: 2, on: 1, count: 2 },
// { day: 4 },
// { day: 5, on: 1, count: 3 }
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment