trees.k 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // parent vector from depth vector
  2. p:{r:@[;;|;]\[(!0)@&1+|/x;x;!#x];(!#x)^'r@'x-1}
  3. // parent children lookup (excludes self-parenting)
  4. cp:{^'[;?x]@=x}
  5. / join the values of x in z with y.
  6. cxn:{r+y*r<{(y|z)&z<x}[*|x]\r*|/x=\:r:z}
  7. / classify the types of child nodes
  8. / 0 lone node, 1 leftmost node, 2 rightmost node, 3 middle node
  9. cls:{1+(-x=!#x)+1+@[&#x;+(-1 1_\:)'.cp[x];+;1 2]}
  10. / spread out the nodes
  11. spr:{y@(-x)_,/(!#y),\:x#-1}
  12. shp:-1_#'*:\
  13. // vertical tree rendering
  14. sh0:{,/'(" ";"┬";"─";"├";"└";"│")x}
  15. t0:{t:(1+^x?!#x)*+s1:(!1+|/y)=\:y
  16. t+:(3+|/'|0>':|\|(!#x)=/:x)*+1_s1,,0
  17. sh0 cxn[1 4;5;t]}
  18. // horizontal tree rendering
  19. sh1:{,/'(" ";"┬";"│";"├";"┐";"┬";"─")x}
  20. t1:{t:spr[x]@+/(0N;t)*~:\=':t:t@\:!|/#'t:|'(y@)\'(!#y)^y
  21. t0:cxn[3 4;6;0^cls[y]@t]
  22. (sh1 0^+t0;+t)}
  23. sh2:{,/'(" ";"┬";"│";"┌";"┐";"┬";"─";"│";"┴";"┼")x}
  24. / center adjust horizontal position
  25. ctr:{$[^(!x)?z; y
  26. 1~c:#x@z; @[y;z;:;@[y:o[x]/[y;x@z];*x@z]]
  27. @[y;z;:;(-c)!+/@[y:o[x]/[y;x@z];x@z]]]}
  28. / center labels
  29. ctl0:{<>((#c)#!2)@&c:,/+(((-':i)-(0,-1_x@i))+(-1_+/1(-|0,|1_)\0,-2!_-0.5+x@i);x@i:&1&x)}
  30. ctl:{ m:(~&/^:)''x
  31. d:,/'(~&//'^:)#'x
  32. (d@'ctl0'm*#''x)@\:!#*x}
  33. pad:{p:x#/:" ",0N;p,/:'y,\:'p}
  34. / mark where node splits to children
  35. frk:{[i;t;r;y;p]shp[t]#@[0^r[cls[y]];;:;].1(7+0 1 0N 2@-2+3^r[cls[y]]@)\1+i@?y@p}
  36. t2:{t:spr[x]@+/(0N;t)*~:\=':t:t@\:!|/#'t:|'(y@)\'(!#y)^y
  37. (h;d):&~^t
  38. p:(~^:)#,/t
  39. h:ctr[cp@y]/[h@<p;&y=!#y]
  40. i:(#*t)/(h;d@<p)
  41. r:@[,/0N+t*0;i;:;]
  42. (sh2@+cxn[3 4;6;frk[i;t;r;y;p]];+shp[t]#r[!#y])}
  43. // depth first preordering of indices
  44. dfo:{<,/{y,,/$[^(!x)?y;!0;o[x]'x[y]]}[cp[x]]'&x=!#x}
  45. // Change all the index references in x "under" permutation <y
  46. redo:{y@x@<y}
  47. // left vector from parent. assumes dfs preorder
  48. lfp:{@[!#x;;:;].1{-1_(*x),x}'\.cp[x]}
  49. // right vector from parent. assumes dfs preorder
  50. rfp:{@[!#x;;:;].1{1_x,*|x}'\.cp[x]}
  51. // right vector from left. assumes dfs preorder
  52. rfl:{c-1+(|!c)^'(|x)?!c:#x}
  53. // left vector from right. assumes dfs preorder
  54. lfr:{(!c)^'x?!c:#x}
  55. // first left child. assumes dfs preorder
  56. / *'cp[x]
  57. flc:!/1(1+)\?:
  58. // first right child. assumes dfs preorder
  59. / (*|)'cp[x]
  60. frc:{(?x)!(rfp[x]@)/1+?x}
  61. / simple interface to printing
  62. shw:{(tr;lb):pad[pd]t2[pd:|/#'x]y
  63. `0:,/+(tr;ctl@x@lb)}