Essays/Parentheses Matching
< Essays
Jump to navigation
Jump to search
x paren y draws lines connecting matching parentheses in phrase y using box drawing characters x . If x is elided then those specified in the J session configuration are used.
depth =: [: +/\ =/\@(''''&~:) * 1 _1 0 {~ '()' i. ] levels=: i.@-@(>./) </ ] i4 =: 2 #.\"(1) 0 ,. ] paren2=: (' ',6 8 10{[) {~ i4@levels@depth@] paren =: (9!:6 '')&$: : (],paren2)
For example:
paren 5!:5 <'depth' [: +/\ =/\@(''''&~:) * 1 _1 0 {~ '()' i. ] └───────┘ paren 5!:6 <'depth' [: ((+/)\) ((((=/)\)@(''''&~:)) * (1 _1 0 ({~) ('()' i. ]))) └──┘ └─────┘ └───────┘ └──┘ └─────────┘ └──┘ └─────────────────┘ └───────────────────────┘ └─────┘ └───────────────────────────────────────────────┘
A similar problem is that of find the minimal enclosing parentheses around a given point in a parenthesized text. mep solves this problem:
NB. y is a string containing parentheses, or (a string containing delimiters);(start,end delimiters) NB. x is [possibly a list of] indexes into y NB. Result is table of (start,end) for the minimal enclosing parentheses NB. for each point of x. mep =: 4 : 0"1 if. L. y do. 'y delims' =. y else. delims =. '()' end. NB. Assign nesting level to each character; make level of ) match ( nlevel =. (+/\ + _1&=) class =. 1 _1 0 {~ delims i. y NB. Create records for sorting: NB. First, the parentheses: level,position,_1 or #x based on class (to sort in order start,ref,end) NB. Then, the requested indexes: level,position,(item# in x) lpc =. (({&nlevel ,. ] ,. (0 _1,#x) {~ ({&class)) I. class ~: 0) , ({&nlevel ,. ] ,. i.@#) x NB. Sort into order; assign interval number to each point; select interval numbers for points NB. of interest; sort back into order of the original x (((-.@(e.&(_1,#x)) (# C.^:_1 (# +/\@:(_1&=))) ])@] { 0 0 , _2 ]\ ((# 1&{"1)~ e.&(_1,#x))) (2&{"1)) /:~ lpc ) 5 6 mep '((0 1 (2 3))4 5)' 1 11 6 10
Contributed by Roger Hui; mep by Henry Rich. An earlier version appeared in the J Forum on 2008-07-31.