Balanced brackets: Difference between revisions

Content added Content deleted
m (→‎JS Functional: Tidying)
Line 3,469: Line 3,469:
'use strict';
'use strict';


// ---------------- BALANCED BRACKETS ----------------
// findUnbalancedBracket :: String -> String -> Maybe Int

const findUnbalancedBracket = strBrackets => strHaystack => {
// firstUnbalancedBracket :: String -> String -> Maybe Int
const
const firstUnbalancedBracket = brackets =>
openBracket = strBrackets[0],
closeBracket = strBrackets[1];
haystack => {
const go = (xs, iDepth, iCharPosn) =>
const [openBracket, closeBracket] = [...brackets];
// iDepth: initial nesting depth (0 = closed)
const go = (xs, iDepth, iCharPosn) =>
// iCharPosn: starting character position
// iDepth: initial nesting depth (0 = closed)
0 < xs.length ? (() => {
// iCharPosn: starting character position
const
0 < xs.length ? (() => {
h = xs[0],
const
tail = xs.slice(1),
h = xs[0],
iNext = iDepth + (
tail = xs.slice(1),
strBrackets.includes(h) ? (
iNext = iDepth + (
openBracket === h ? (
brackets.includes(h) ? (
1
openBracket === h ? (
) : -1
1
) : 0
) : -1
);
) : 0
return 0 > iNext ? (
);
Just(iCharPosn) // Unmatched closing bracket.
return 0 > iNext ? (
) : 0 < tail.length ? go(
Just(iCharPosn) // Unmatched closing bracket.
tail, iNext, 1 + iCharPosn
) : 0 < tail.length ? go(
) : 0 !== iNext ? (
tail, iNext, 1 + iCharPosn
) : 0 !== iNext ? (
Just(iCharPosn)
) : Nothing();
})() : 0 !== iDepth ? (
Just(iCharPosn)
Just(iCharPosn)
) : Nothing();
) : Nothing();
})() : 0 !== iDepth ? (
return go([...haystack], 0, 0);
Just(iCharPosn)
};
) : Nothing();
return go(strHaystack.split(''), 0, 0);
};




// TEST -----------------------------------------------
// ---------------------- TEST -----------------------
// main :: IO ()
// main :: IO ()
const main = () => {
const main = () => {
Line 3,519: Line 3,520:
' '.repeat(1 + iUnMatched) + '^'
' '.repeat(1 + iUnMatched) + '^'
)(
)(
findUnbalancedBracket('[]')(strSample)
firstUnbalancedBracket('[]')(strSample)
);
);
}).join('\n')
}).join('\n')
);
);
};
};



// Int -> String
// Int -> String
Line 3,533: Line 3,535:




// GENERIC --------------------------------------------
// --------------------- GENERIC ---------------------


// Just :: a -> Maybe a
// Just :: a -> Maybe a
Line 3,541: Line 3,543:
Just: x
Just: x
});
});



// Nothing :: Maybe a
// Nothing :: Maybe a
Line 3,547: Line 3,550:
Nothing: true,
Nothing: true,
});
});



// enumFromTo :: Int -> Int -> [Int]
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m => n =>
const enumFromTo = m =>
Array.from({
n => !isNaN(m) ? (
length: 1 + n - m
Array.from({
}, (_, i) => m + i);
length: 1 + n - m
}, (_, i) => m + i)
) : enumFromTo_(m)(n);



// maybe :: b -> (a -> b) -> Maybe a -> b
// maybe :: b -> (a -> b) -> Maybe a -> b
const maybe = v => f => m =>
const maybe = v =>
m.Nothing ? v : f(m.Just);
// Default value (v) if m is Nothing, or f(m.Just)
f => m => m.Nothing ? (
v
) : f(m.Just);


// ---
// ---