Skip to content
TurtleKitty edited this page May 11, 2019 · 3 revisions

stream

A stream is a window to the world outside the program: a source of data or a sink. It can be a connection to a file, a pipe, a socket, or even a text. Some methods work on both stream types; others make sense only for one or the other.

predicate

(stream? x)

messages

stdin.type     ; (source stream)
stdout.type    ; (sink stream)
stderr.type    ; (sink stream)

stdin.to-bool  ; true

stdin.input?   ; true
stdin.output?  ; false
stdout.output? ; true

stdin.open?    ; true
stdin.to-bool  ; true
stderr.open?   ; true
stderr.to-bool ; true
stderr.close   ; null
stderr.open?   ; false
stderr.to-bool ; false

source messages

(def sexprs "(foo (bar baz)) (quux 2 3)")
(def str sexprs.to-stream)

str.ready?  ; true
str.read    ; (foo (bar baz))

(def sexprs "(foo (bar baz)) (quux 2 3)") ; "(foo (bar baz)) (quux 2 3)"
(def str sexprs.to-stream)                ; #<input port "(string)">

str.ready?  ; true
str.read    ; (foo (bar baz))
str.read    ; (quux 2 3)
str.read    ; EOF

(def fb "foonballardy!!!")

(let (p fb.to-stream)
    p.peek-char   ; "f"
    p.peek-char   ; "f"
    p.read-char   ; "f"
    p.peek-char   ; "o"
    p.read-char   ; "o"
    p.read-char   ; "o"
    p.read-char)  ; "n"

(let (lines "uno\ndos\ntres")
   lines.to-stream.read-line) ; "uno"

; stream.to-list reads all lines until EOF and returns a list of texts

(let (lines "uno\ndos\ntres")
   lines.to-stream.to-list)   ; ("uno" "dos" "tres")

(let (lines "uno\ndos\ntres")
   lines.to-stream.to-text)   ; "uno\ndos\ntres"

(let (obj-source sexprs.to-stream)
   obj-source.read-seq)       ; (seq (foo (bar baz)) (quux 2 3))

; some useful parsing primitives

(let (p fb.to-stream)
    (p.read-n 6))             ; "foonba"

(let (p fb.to-stream)
    (p.read-while "bfno"))    ; "foonb"

(let (p fb.to-stream)
    (p.read-until "!"))       ; "foonballardy"

(let (p fb.to-stream)
    (p.skip-n 4)
    p.peek-char)              ; "b"

(let (p fb.to-stream)
    (p.skip-while "fo")
    p.peek-char)              ; "n"

(let (p fb.to-stream)
    (p.skip-until "b")
    p.peek-char)              ; "b"

sink messages

(stdout.write "foo") ; serialize object
   ; "foo"null

(stdout.print "foo") ; display text
   ; foonull

(stdout.say "foo")   ; like print, but adds a \n to the end
   ; foo
   ; null

stdout.nl            ; newline
   ;
   ; null

stdout.flush         ; flush any buffered output
   ; null
Clone this wiki locally