sourcedemos/xetal-pipes/stages/Pipes.xtl

1⍝# Pipes: what every stage shares. A stage's input is one text, its 2⍝# lines each ending in a newline; l_ines numbers every character by 3⍝# the line it is on, so a stage chooses or reorders whole lines with 4⍝# a mask or a grade over those numbers, never a loop over lines. 5 6⍝ The end of the input: X_eTaL cannot yet tell when standard input has 7⍝ ended ([]R_EAD fails, docs/xetal-asks.md), so the stage's wrapper 8⍝ writes this line after the real input. 9end ← "<<xetal-end-of-input>>" 10nl ← f̲irst "\n" 11⍝ One character 0: the mark that the input has ended, and the padding 12⍝ of short lines (it sorts before every other character). 13z ← 1 t̲ake ⎕U̲CHAR 0 14 15⍝ Whether a text ends with the mark. 16ʰe̲nded ← { t → (-1 t̲ake t) m̲atch z } 17 18⍝ One line of standard input with its newline; the mark at the end. 19ʰr̲ead1 ← { @ → l ← ⎕R̲EAD @◆ l m̲atch end ? z◆ l c̲at nl } 20 21⍝ Up to n lines (the mark at the end once the input has ended): halves 22⍝ read one after the other, so the text is copied about log n times, 23⍝ not once per line. 24ʰr̲eadn ← { n → 25 n ≤ 1 ? ʰr̲ead1 @ 26 a ← ʰr̲eadn n d̲iv 2 27 ʰe̲nded a ? a 28 a c̲at ʰr̲eadn n − n d̲iv 2 29} 30 31⍝ Everything up to the end, n lines first, then 2n, 4n, ... 32ʰr̲eadall ← { n → 33 a ← ʰr̲eadn n 34 ʰe̲nded a ? -1 d̲rop a 35 a c̲at ʰr̲eadall 2 × n 36} 37 38⍝# Standard input, every line ending in a newline. 39ˡr̲ead ← { @ → ʰr̲eadall 64 } 40 41⍝# Write a text to standard output as it is (no newline added); how 42⍝# many characters. 43ˡo̲ut ← { t → t ⎕N̲PUT "/dev/stdout" } 44 45⍝# Each character's line number, from 1 (a newline is on the line it 46⍝# ends). 47ˡl̲ines ← { t → 1 + '+ s̲\ (t̲ally t) t̲ake 0 c̲at 1 × t = nl } 48 49⍝# How many lines. 50ˡc̲ount ← { t → '+ r̲/ 1 × t = nl } 51 52⍝# The lines whose mask (one per line) is 1. 53ˡk̲eep ← { mask t → ((ˡl̲ines t) s̲elect mask) r̲eplicate t } 54 55⍝# The lines as the rows of a matrix, each padded with character 0 to 56⍝# the longest (its newline left out). 57ˡm̲atrix ← { t → 58 ends ← w̲here t = nl 59 starts ← (t̲ally ends) t̲ake 1 c̲at 1 + ends 60 lens ← ends − starts 61 w ← 1 m̲ax 'm̲ax r̲/ 0 c̲at lens 62 inside ← lens '> t̲able o̲ffsets w 63 at ← (starts '+ t̲able o̲ffsets w) × inside 64 (at + (1 − inside) × 1 + t̲ally t) s̲elect t c̲at z 65}