Jump to content

Balanced brackets: Difference between revisions

m
m (→‎JS Functional: Tidying)
Line 3,469:
'use strict';
 
// ---------------- BALANCED BRACKETS ----------------
// findUnbalancedBracket :: String -> String -> Maybe Int
 
const findUnbalancedBracket = strBrackets => strHaystack => {
// findUnbalancedBracketfirstUnbalancedBracket :: String -> String -> Maybe Int
const
const firstUnbalancedBracket = brackets =>
openBracket = strBrackets[0],
closeBrackethaystack => strBrackets[1];{
const go = (xs, iDepthconst [openBracket, iCharPosn)closeBracket] => [...brackets];
//const iDepth:go initial nesting depth= (0xs, =iDepth, closediCharPosn) =>
// iCharPosniDepth: startinginitial nesting depth (0 character= positionclosed)
0 < xs.length ? (()// =>iCharPosn: {starting character position
const0 < xs.length ? (() => {
h = xs[0],const
tail h = xs.slice(1)[0],
iNext = iDepth + tail = xs.slice(1),
strBrackets.includes(h)iNext ?= iDepth + (
openBracket === brackets.includes(h) ? (
1openBracket === h ? (
) : - 1
) : 0-1
); : 0
return 0 > iNext ? ( );
Just(iCharPosn)return //0 Unmatched> closingiNext bracket.? (
) : 0 < tail.length ? go Just(iCharPosn) // Unmatched closing bracket.
tail,) iNext,: 10 < tail.length +? iCharPosngo(
) : 0 !== tail, iNext, 1 ?+ (iCharPosn
) : Nothing0 !== iNext ? ();
Just(iCharPosn)
) : Nothing();
})() : 0 !== iDepth ? (
Just(iCharPosn)
) : Nothing();
})return go()[...haystack], :0, 0 !== iDepth ? ();
Just(iCharPosn)};
) : Nothing();
return go(strHaystack.split(''), 0, 0);
};
 
 
// TEST ------------------------ TEST -----------------------
// main :: IO ()
const main = () => {
Line 3,519 ⟶ 3,520:
' '.repeat(1 + iUnMatched) + '^'
)(
findUnbalancedBracketfirstUnbalancedBracket('[]')(strSample)
);
}).join('\n')
);
};
 
 
// Int -> String
Line 3,533 ⟶ 3,535:
 
 
// GENERIC ----------------------- GENERIC ---------------------
 
// Just :: a -> Maybe a
Line 3,541 ⟶ 3,543:
Just: x
});
 
 
// Nothing :: Maybe a
Line 3,547 ⟶ 3,550:
Nothing: true,
});
 
 
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m => n =>
Array.fromn => !isNaN(m) ? ({
length: 1 + n - mArray.from({
}, (_, i) => m length: 1 + i);n - m
}, (_, i) => m + i)
) : enumFromTo_(m)(n);
 
 
// maybe :: b -> (a -> b) -> Maybe a -> b
const maybe = v => f => m =>
m.Nothing// ?Default value (v) if m is Nothing, :or f(m.Just);
f => m => m.Nothing ? (
const v
) : f(m.Just);
 
// ---
9,659

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.