Last active
February 1, 2024 18:20
-
-
Save fResult/571b0913dc0590b7f964eabc428cfcd5 to your computer and use it in GitHub Desktop.
copy from the Haskell code in the "Mathematics for Working Programmer class - Day 3-4"
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
// MSS - Maximum Sum Segment problem | |
// MSS = maximum . map sum . concat . map inits . tails | |
// Playground - https://tsplay.dev/mpzE6w | |
function tail<T>(xs: T[]): T[] { | |
return xs.slice(1) | |
} | |
function init<T>(xs: T[]): T[] { | |
return xs.slice(0, -1) | |
} | |
function tails<T>([x, ...xs]: T[]): T[][] { | |
if (x === undefined && xs.length === 0) return [[]] | |
return [[x, ...xs], ...tails(xs)] | |
} | |
function inits<T>([x, ...xs]: T[]): T[][] { | |
if (x === undefined) return [[]] | |
if (xs.length === 0) return [[], [x]] | |
return [...inits([x, ...init(xs)]), [x, ...xs]] | |
} | |
function maximum([x, ...xs]: number[]): number { | |
if (x === undefined) throw Error('List has no member') | |
if (xs.length === 0) return x | |
return Math.max(x, maximum(xs)) | |
} | |
function map<T, R>(f: (x: T) => R): (xs: T[]) => R[] { | |
return function forXs(xs) { | |
return xs.map(f) | |
} | |
} | |
// https://zvon.org/other/haskell/Outputprelude/concat_f.html | |
function concat<T>(xss: T[][]): T[] { | |
return xss.flat() | |
} | |
function sum([x, ...xs]: number[]): number { | |
if (x === undefined) return 0 | |
if (xs.length === 0) return x | |
return x + sum(xs) | |
} | |
const input: number[] = [1, 2, -1, 0, 3, -1] | |
let it | |
console.log('tails input', it = tails(input)) | |
console.log('map inits it', it = map(inits)(it)) | |
console.log('concat it', it = concat(it)) | |
console.log('map sum it', it = map(sum)(it)) | |
console.log('maximum it', maximum(it)) | |
const mss = compose(maximum, map(sum), concat, map(inits), tails) | |
console.log('mss = (maximum . map sum . concat . map inits . tails) input', mss(input)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment