goal

package module
v0.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 2, 2023 License: ISC Imports: 16 Imported by: 2

README

Goal

pkg.go.dev godocs.io

Goal is an embeddable array programming language with a bytecode interpreter, written in Go. It provides both a command line intepreter (that can be used in the REPL), and a library interface. The core features are mostly there and tested, so Goal is usable both for writing useful short scripts and playing with the REPL. User testing and bug reports are welcome!

Like in most array programming languages, Goal's builtins vectorize operations on immutable arrays, and encourage a functional style for control and data transformations, supported by a simple dynamic type system with little abstraction, and mutable variables (but no mutable values).

It's main distinctive features are as follows:

  • Syntax inspired mainly from the K language, but with quite a few deviations. For example, backquotes produce Go-like raw strings instead of symbols, rx/[a-z]/ is a regular expression literal (checked and processed at compile-time), and there is a Perl-style qq string interpolation with custom delimiter. On the other side, there are no tacit compositions, and digraph operator verbs and adverbs are gone or done differently (except for global assignment with ::).
  • Primitive semantics are both inspired from the ngn/k variant of the K language and BQN. For example, group, classify, shifts, windows, find (index of) and occurrence count take after BQN's semantics. Multi-dimensional versions, when present in BQN, have been left out, though, as Goal has only free-form immutable arrays, like K. Some primitives use words instead of symbols (like ocount for occurrence count). Also, K-like dictionaries are supported, but not tables.
  • Unlike in typical array languages, strings are atoms, and common string handling functions (like index, substr or trim) have been integrated into the primitives, including regular expression functions.
  • Error handling makes a distinction between fatal errors (panics) and recoverable errors which are handled as values.
  • Easily embeddable and extensible in Go, meaning easy access to the standard library.
  • Integrated support for csv and time handling.
  • Array performance is unsurprising and good enough most of the time, with basic (but good in code with limited branching) variable liveness analysis to reduce cloning by reusing dead immutable arrays, though it is not a goal to reach state-of-the-art (no SIMD, and there is still room for more special code and specialized algorithms). Scalar performance is typical for a bytecode-compiled interpreter (without JIT), somewhat slower than a C bytecode interpreter (value representation in Go is somewhat less compact than how it can be done in C).

If this list is not enough to satisfy your curiosity, there's also a Why.md text for you. You can also read the Credits.md to know about main inspiration sources for the language. Last, but not least, there are some implementation notes too.

Install

To install the command line interpreter, first do the following:

  • Install the go compiler.
  • Add $(go env GOPATH)/bin to your $PATH (for example export PATH="$PATH:$(go env GOPATH)/bin").

Then you can build the intepreter with:

go install ./cmd/goal

Alternatively, you may type go build -o /path/to/bin/goal ./cmd/goal to put the resulting binary in a custom location in your $PATH.

The goal command should now be available. Type goal --help for command-line usage.

Typing just goal opens the REPL. For a better experience using the REPL (to get typical keyboard shortcuts), you can install the readline wrapper rlwrap program (available as a package in most systems), and then use instead rlwrap goal.

Editor support

Examples

A few short examples can be found in the testdata/scripts directory. Because they're used for testing, they come along an expected result after a /RESULT: comment.

Also, various code generation scripts in the toplevel scripts directory are written in Goal.

Documentation

Documentation consists of the REPL help system with a short description and/or examples for all implemented features. Some prior knowledge of another array language, in particular K, can be useful, but not necessary: the best way to learn and discover the language is to play with it in the REPL. The full contents are replicated below. See also this short FAQ.

TOPICS HELP
Type help TOPIC or h TOPIC where TOPIC is one of:

"s"     syntax
"t"     value types
"v"     verbs (like +*-%,)
"nv"    named verbs (like in, sign)
"a"     adverbs ('/\)
"io"    IO verbs (like say, open, read)
"tm"    time handling
"rt"    runtime system
op      where op is a builtin's name (like "+" or "in")

Notations:
        n (number) i (integer) s (string) r (regexp) d (dict)
        f (function) F (dyadic function) e (error) h (handle)
        x,y,z (any other) N,I,S,X,Y,A (arrays)

SYNTAX HELP
numbers         1     1.5     0b0110     1.7e-3     0xab     0n     0w     3h2m
strings         "text\xff\u00F\n"   "\""   "\u65e5"   "interpolated $var"
                qq/$var\n or ${var}/   qq#text#  (delimiters :+-*%!&|=~,^#_?@/')
raw strings     `anything until first backquote`     `literal \, no escaping`
                rq/anything until single slash/      rq#doubling ## escapes #
arrays          1 2 -3 4      1 "ab" -2 "cd"      (1 2;"a";3 "b";(4 2;"c");*)
regexps         rx/[a-z]/      (see https://pkg.go.dev/regexp/syntax for syntax)
verbs           : + - * % ! & | < > = ~ , ^ # _ $ ? @ . ::   (right-associative)
                abs bytes ceil error ...
adverbs         / \ ' (alone or after expr. with no space)    (left-associative)
expressions     2*3+4 -> 14      1+|2 3 4 -> 5 4 3      +/'(1 2 3;4 5 6) -> 6 15
separator       ; or newline except when ignored after {[( and before )]}
variables       a  b.c  f  data  t1
assign          a:2 (local within lambda, global otherwise)        a::2 (global)
op assign       a+:1 (sugar for a:a+1)         a-::2 (sugar for a::a-2)
list assign     (a;b;c):x (where 2<#x)         (a;b):1 2;b -> 2
eval. order     apply:f[e1;e2]   apply:e1 op e2                      (e2 before)
                list:(e1;e2)     seq: [e1;e2]     lambda:{e1;e2}     (e1 before)
sequence        [a:2;b:a+3;a+10] -> 12
index/apply     x[y] or x y is sugar for x@y; x[] ~ x[*] ~ x[!#x] ~ x (arrays)
index deep      x[y;z;...] is sugar for x.(y;z;...) (except for x in (?;and;or))
index assign    x[y]:z is sugar for x:@[x;y;:;z]           (or . for x[y;...]:z)
index op assign x[y]op:z is sugar for x:@[x;y;op;z]              (for symbol op)
lambdas         {x+y-z}[3;5;7] -> 1       {[a;b;c]a+b-c}[3;5;7] -> 1
projections     +[2;] 3 -> 5              (2+) 3 -> 5      (partial application)
cond            ?[1;2;3] -> 2     ?[0;2;3] -> 3    ?[0;2;"";3;4] -> 4
and/or          and[1;2] -> 2   and[1;0;3] -> 0   or[0;2] -> 2   or[0;0;0] -> 0
return          [1;:2;3] -> 2                       (a : at start of expression)
try             'x is sugar for ?["e"~@x;:x;x]         (return if it's an error)
comments        from line with a single / until line with a single \
                or from / (after space or start of line) to end of line

TYPES HELP
atom    array   name            examples
n       N       number          0       1.5       !5       1.2 3 1.8
s       S       string          "abc"   "d"       "a" "b" "c"
r               regexp          rx/[a-z]/         rx/\s+/
d               dictionary      "a" "b"!1 2       keys!values
f               function        +      {x*2}      (1-)      %[;2]
h               handle          open "/path/to/file"    "w" open "/path/to/file"
e               error           error "msg"
        A       generic array   ("a" 1;"b" 2;"c" 3)     (+;-;*;"any")

VERBS HELP
:x  identity    :[42] -> 42            (recall that : is also syntax for return)
x:y right       2:3 -> 3            "a":"b" -> "b"
+x  flip        +(1 2;3 4) -> (1 3;2 4)                   +42 -> ,,42
n+n add         2+3 -> 5            2+3 4 -> 5 6
s+s concat      "a"+"b" -> "ab"     "a" "b"+"c" -> "ac" "bc"
-n  negate      - 2 3 -> -2 -3      -(1 2.5;3 4) -> (-1 -2.5;-3 -4)
n-n subtract    5-3 -> 2            5 4-3 -> 2 1
s-s trim suffix "file.txt"-".txt" -> "file"
*x  first       *3 2 4 -> 3         *"ab" -> "ab"         *(+;*) -> +
n*n multiply    2*3 -> 6            1 2 3*3 -> 3 6 9
s*i repeat      "a"*3 2 1 0 -> "aaa" "aa" "a" ""
%X  classify    %7 8 9 7 8 9 -> 0 1 2 0 1 2      %"a" "b" "a" -> 0 1 0
x%y divide      3%2 -> 1.5          3 4%2 -> 1.5 2
!i  enum        !5 -> 0 1 2 3 4
!d  keys        !"a" "b"!1 2 -> "a" "b"
!I  odometer    !2 3 -> (0 0 0 1 1 1;0 1 2 0 1 2)
i!i range       2!5 -> 2 3 4        5!2 -> !0
i!s colsplit    3!"abcdefghijk" -> "abc" "def" "ghi" "jk"      (i-bytes strings)
i!Y colsplit    2!!6 -> (0 1;2 3;4 5)            2!"a" "b" "c" -> ("a" "b";,"c")
X!Y dict        d:"a" "b"!1 2;d "a" -> 1
&I  where       &0 0 1 0 0 0 1 -> 2 6            &2 3 -> 0 0 1 1 1
&d  keys where  &"a""b""c""d"!0 1 1 0 -> "b" "c"
x&y min         2&3 -> 2        4&3 -> 3         "b"&"a" -> "a"
|X  reverse     |!5 -> 4 3 2 1 0
x|y max         2|3 -> 3        4|3 -> 4         "b"|"a" -> "b"
<X  ascend      <3 5 4 -> 0 2 1          (index permutation for ascending order)
x<y less        2<3 -> 1        "c" < "a" -> 0
>X  descend     >3 5 4 -> 1 2 0         (index permutation for descending order)
x>y greater     2>3 -> 0        "c" > "a" -> 1
=s  fields      ="a b\tc\nd  e" -> "a" "b" "c" "d" "e"       (unicode space too)
=I  group       =1 0 2 1 2 -> (,1;0 3;2 4)       =-1 2 -1 2 -> (!0;!0;1 3)
=d  group keys  ="a""b""c"!0 1 0 -> ("a" "c";,"b")
f=Y group by    {2 mod x}=!10 -> (0 2 4 6 8;1 3 5 7 9)
x=y equal       2 3 4=3 -> 0 1 0        "ab" = "ba" -> 0
~x  not         ~0 1 2 -> 1 0 0         ~"a" "" "0" -> 0 1 0
x~y match       3~3 -> 1        2 3~3 2 -> 0        ("a";%)~("b";%) -> 0 1
,x  enlist      ,1 -> ,1        #,2 3 -> 1               (list with one element)
d,d merge       ("a""b"!1 2),"b""c"!3 4 -> "a""b""c"!1 3 4
x,y join        1,2 -> 1 2              "ab" "c","d" -> "ab" "c" "d"
^X  sort        ^3 5 0 -> 0 3 5         ^"ca" "ab" "bc" -> "ab" "bc" "ca"
i^s windows     2^"abcd" -> "ab" "bc" "cd"                     (i-bytes strings)
i^Y windows     2^!4 -> (0 1;1 2;2 3)
s^s trim        " []"^"  [text]  " -> "text"      ""^" \nstuff\t" -> "stuff"
X^Y without     2 3^1 1 2 3 3 4 -> 1 1 4
#x  length      #2 4 5 -> 3       #"ab" "cd" -> 2       #42 -> 1      #"ab" -> 1
i#y take        2#6 7 8 -> 6 7    4#6 7 8 -> 6 7 8 6 (cyclic)       3#1 -> 1 1 1
s#s count       "ab"#"cabdab" "cd" "deab" -> 2 0 1
f#y replicate   {0 1 1 0}#4 1 5 3 -> 1 5          {x>0}#2 -3 1 -> 2 1
X#Y keep only   2 3#1 1 2 3 3 4 -> 2 3 3
_n  floor       _2.3 -> 2               _1.5 3.7 -> 1 3
_s  to lower    _"ABC" -> "abc"         _"AB" "CD" -> "ab" "cd"
i_s drop bytes  2_"abcde" -> "cde"      -2_"abcde" -> "abc"
i_y drop        2_3 4 5 6 -> 5 6        -2_3 4 5 6 -> 3 4
s_i delete      "abc"_1 -> "ac"
X_i delete      6 7 8 9_1 -> 6 8 9      6 7 8 9_-3 -> 6 8 9
s_s trim prefix "pref-"_"pref-name" -> "name"
I_s cut string  1 3_"abcdef" -> "bc" "def"                         (I ascending)
I_Y cut         2 5_!10 -> (2 3 4;5 6 7 8 9)                       (I ascending)
f_y weed out    {0 1 1 0}_4 1 5 3 -> 4 3          {x>0}_2 -3 1 -> ,-3
$x  string      $2 3 -> "2 3"       $"text" -> "\"text\""
i$s pad         3$"a" -> "a  "      -3$"1" "23" "456" -> "  1" " 23" "456"
s$y cast        "i"$2.3 -> 2        "i"$"ab" -> 97 98          "s"$97 98 -> "ab"
s$s parse num   "n"$"1.5" -> 1.5    "n"$"2" "1e+7" "0b100" -> 2 1e+07 4
X$y binsearch   2 3 5 7$8 2 7 5 5.5 3 0 -> 4 1 4 3 3 2 0           (x ascending)
?i  uniform     ?2 -> 0.6046602879796196 0.9405090880450124
?X  uniq        ?2 2 3 4 3 3 -> 2 3 4
i?i roll        5?100 -> 10 51 21 51 37
i?Y roll array  5?"a" "b" "c" -> "c" "a" "c" "c" "b"
i?i deal        -5?100 -> 19 26 0 73 94                        (always distinct)
i?Y deal array  -3?"a""b""c" -> "a""c""b"                      (always distinct)
s?r rindex      "abcde"?rx/b../ -> 1 3                           (offset;length)
s?s index       "a = a + 1"?"=" "+" -> 2 6
d?y find key    ("a" "b"!3 4)?4 -> "b"       ("a" "b"!3 4)?5 -> ""
X?y find        9 8 7?8 -> 1                 9 8 7?6 -> 3
@x  type        @2 -> "n"    @"ab" -> "s"    @2 3 -> "N"     @+ -> "f"
s@i substr      "abcdef"@2  -> "cdef"                                (s[offset])
r@s match       rx/^[a-z]+$/"abc" -> 1       rx/\s/"abc" -> 0
r@s find group  rx/([a-z])(.)/"&a+c" -> "a+" "a" "+"     (whole match, group(s))
f@y apply       (|)@1 2 -> 2 1                      (like |[1 2] -> 2 1 or |1 2)
d@y at key      ("a" "b"!1 2)@"a" -> 1
X@i at          7 8 9@2 -> 9         7 8 9[2 0] -> 9 7       7 8 9@-2 -> 8
.s  reval       ."2+3" -> 5    (restricted eval with new context: see also eval)
.e  get error   .error "msg" -> "msg"
.d  values      ."a" "b"!1 2 -> 1 2             ("a" "b"!1 2)[] -> 1 2 (special)
s.I substr      "abcdef"[2;3] -> "cde"                        (s[offset;length])
r.y findN       rx/[a-z]/["abc";2] -> "a""b"    rx/[a-z]/["abc";-1] -> "a""b""c"
r.y findN group rx/[a-z](.)/["abcdef";2] -> ("ab" "b";"cd" "d")
f.y applyN      {x+y}.2 3 -> 5       {x+y}[2;3] -> 5
X.y at deep     (6 7;8 9)[0;1] -> 7  (6 7;8 9)[;1] -> 7 9
«X  shift       «8 9 -> 9 0    «"a" "b" -> "b" ""   (ASCII alternative: shift x)
x«Y shift       "a" "b"«1 2 3 -> 3 "a" "b"
»X  rshift      »8 9 -> 0 8    »"a" "b" -> "" "a"  (ASCII alternative: rshift x)
x»Y rshift      "a" "b"»1 2 3 -> "a" "b" 1

::x         get global  a:3;::"a" -> 3
x::y        set global  "a"::3;a -> 3
@[d;y;f]    amend       @["a""b""c"!7 8 9;"a""b""b";10+] -> "a""b""c"!17 28 9
@[X;i;f]    amend       @[7 8 9;0 1 1;10+] -> 17 28 9
@[d;y;F;z]  amend       @["a""b""c"!7 8 9;"a";:;42] -> "a""b""c"!42 8 9
@[X;i;F;z]  amend       @[7 8 9;1 2 0;+;10 20 -10] -> -3 18 29
.[X;y;f]    deep amend  .[(6 7;8 9);0 1;-] -> (6 -7;8 9)
.[X;y;F;z]  deep amend  .[(6 7;8 9);(0 1 0;1);+;10] -> (6 27;8 19)
                        .[(6 7;8 9);(*;1);:;42] -> (6 42;8 42)
.[f;x;f]    try         .[+;2 3;{"msg"}] -> 5   .[+;2 "a";{"msg"}] -> "msg"

NAMED VERBS HELP
abs n      abs value    abs -3 -1.5 2 -> 3 1.5 2
bytes s    byte-count   bytes "abc" -> 3
ceil x     ceil/upper   ceil 1.5 -> 2       ceil "ab" -> "AB"
csv s      csv read     csv "1,2,3" -> ,"1" "2" "3"
csv A      csv write    csv ,"1" "2" "3" -> "1,2,3\n"
error x    error        r:error "msg"; (@r;.r) -> "e" "msg"
eval s     comp/run     a:5;eval "a+2" -> 7         (unrestricted variant of .s)
firsts X   mark firsts  firsts 0 0 2 3 0 2 3 4 -> 1 0 1 1 0 0 0 1
json s     parse json   ^json `{"a":true,"b":"text"}` -> "a" "b"!(1;"text")
nan n      isNaN        nan (0n;2;sqrt -1) -> 1 0 1
ocount X   occur-count  ocount 3 4 5 3 4 4 7 -> 0 0 0 1 1 2 0
panic s    panic        panic "msg"               (for fatal programming-errors)
rx s       comp. regex  rx "[a-z]"      (like rx/[a-z]/ but compiled at runtime)
sign n     sign         sign -3 -1 0 1.5 5 -> -1 -1 0 1 1

s csv s    csv read     " " csv "1 2 3" -> ,"1" "2" "3"       (" " as separator)
s csv A    csv write    " " csv ,"1" "2" "3" -> "1 2 3\n"     (" " as separator)
x in s     contained    "bc" "ac" in "abcd" -> 1 0
x in Y     member of    2 3 in 0 2 4 -> 1 0
n mod n    modulus      3 mod 5 4 3 -> 2 1 0
n nan n    fill NaNs    42 nan (1.5;sqrt -1) -> 1.5 42
i rotate Y rotate       2 rotate 7 8 9 -> 9 7 8         -2 rotate 7 8 9 -> 8 9 7

sub[r;s]   regsub       sub[rx/[a-z]/;"Z"] "aBc" -> "ZBZ"
sub[r;f]   regsub       sub[rx/[A-Z]/;_] "aBc" -> "abc"
sub[s;s]   replace      sub["b";"B"] "abc" -> "aBc"
sub[s;s;i] replaceN     sub["a";"b";2] "aaa" -> "bba"       (stop after 2 times)
sub[S]     replaceS     sub["b" "d" "c" "e"] "abc" -> "ade"
sub[S;S]   replaceS     sub["b" "c";"d" "e"] "abc" -> "ade"

eval[s;loc;pfx]         like eval s, but provide loc as location (usually a
                        path), and prefix pfx+"." for globals

utf8.rcount s           utf8.rcount "aπc" -> 3           (number of code points)
utf8.valid s            utf8.valid "aπc" -> 1            utf8.valid "a\xff" -> 0
x utf8.valid s          "b" utf8.valid "a\xff" -> "ab"  (replace invalid with x)

MATH: atan2, cos, exp, log, round, sin, sqrt

ADVERBS HELP
f'x    each      #'(4 5;6 7 8) -> 2 3
x F'y  each      2 3#'4 5 -> (4 4;5 5 5)    {(x;y;z)}'[1;2 3;4] -> (1 2 4;1 3 4)
F/x    fold      +/!10 -> 45
F\x    scan      +\!10 -> 0 1 3 6 10 15 21 28 36 45
x F/y  fold      5 6+/!4 -> 11 12                    {x+y-z}/[5;4 3;2 1] -> 9
x F\y  scan      5 6+\!4 -> (5 6;6 7;8 9;11 12)      {x+y-z}\[5;4 3;2 1] -> 7 9
i f/y  do        3{x*2}/4 -> 32
i f\y  dos       3{x*2}\4 -> 4 8 16 32
f f/y  while     {x<100}{x*2}/4 -> 128
f f\y  whiles    {x<100}{x*2}\4 -> 4 8 16 32 64 128
f/x    converge  {1+1.0%x}/1 -> 1.618033988749895    {-x}/1 -> -1
f\x    converges {_x%2}\10 -> 10 5 2 1 0             {-x}\1 -> 1 -1
s/S    join      ","/"a" "b" "c" -> "a,b,c"
s\s    split     ","\"a,b,c" -> "a" "b" "c"          ""\"aπc" -> "a" "π" "c"
r\s    split     rx/[,;]/\"a,b;c" -> "a" "b" "c"
i s\s  splitN    (2) ","\"a,b,c" -> "a" "b,c"
I/x    encode    24 60 60/1 2 3 -> 3723              2/1 1 0 -> 6
I\x    decode    24 60 60\3723 -> 1 2 3              2\6 -> 1 1 0

IO/OS HELP
chdir s     change current working directory to s, or return an error
close h     flush any buffered data, then close filehandle h
env s       get environment variable s, or an error if unset
            return a dictionary representing the whole environment if s~""
flush h     flush any buffered data for filehandle h
import s    read/eval wrapper roughly equivalent to eval[read path;path;pfx]
            where 1) path~s or is derived from s by appending ".goal" and/or
                     prefixing with env "GOALLIB"
                  2) pfx is path's basename without extension
open s      open path s for reading, returning a filehandle (h)
print s     print "Hello, world!\n"     (uses implicit $x for non-string values)
read h      read from filehandle h until EOF or an error occurs
read s      read file named s                     lines:"\n"\read"/path/to/file"
run s       run command s or S (with arguments)   run "pwd"        run "ls" "-l"
            inherits stdin and stderr, returns its standard output or an error
            dict with keys "code" "msg" "out"
say s       same as print, but appends a newline                   say !5
shell s     same as s run "/bin/sh"                                shell "ls -l"

x env s     set environment variable x to s, or return an error
x env 0     unset environment variable x, or clear environment if x~""
x import s  same as import s, but using prefix x for globals
x open s    open path s with mode x in "r" "r+" "w" "w+" "a" "a+"
            or pipe from (x~"-|") or to (x~"|-") command s or S
x print s   print s to filehandle/name x        "/path/to/file" print "content"
i read h    read i bytes from reader h or until EOF, or an error occurs
s read h    read from reader h until 1-byte s, EOF, or an error occurs
x run s     same as run s but with input string x as stdin
x say s     same as print, but appends a newline

ARGS        command-line arguments, starting with script name
STDIN       standard input filehandle (buffered)
STDOUT      standard output filehandle (buffered)
STDERR      standard error filehandle (buffered)

TIME HELP
time cmd              time command with current time
cmd time t            time command with time t
time[cmd;t;fmt]       time command with time t in given format
time[cmd;t;fmt;loc]   time command with time t in given format and location

Time t should be either an integer representing unix epochtime, or a string in
the given format (RFC3339 format layout "2006-01-02T15:04:05Z07:00" is the
default). See https://pkg.go.dev/time for information on layouts and locations,
as goal uses the same conventions as Go's time package. Supported values for
cmd are as follows:

    cmd (s)       result (type)
    ------        -------------
    "clock"       hour, minute, second (I)
    "date"        year, month, day (I)
    "day"         day number (i)
    "hour"        0-23 hour (i)
    "minute"      0-59 minute (i)
    "second"      0-59 second (i)
    "unix"        unix epoch time (i)
    "unixmicro"   unix (microsecond version, only for current time) (i)
    "unixmilli"   unix (millisecond version, only for current time) (i)
    "unixnano"    unix (nanosecond version, only for current time) (i)
    "week"        year, week (I)
    "weekday"     0-7 weekday starting from Sunday (i)
    "year"        year (i)
    "yearday"     1-365/6 year day (i)
    "zone"        name, offset in seconds east of UTC (s;i)
    format (s)    format time using given layout (s)

RUNTIME HELP
rt.prec i       set floating point formatting precision to i     (default -1)
rt.seed i       set non-secure pseudo-rand seed to i     (used by the ? verb)
rt.time[s;i]    eval s for i times (default 1), return average time (ns)
rt.time[f;x;i]  call f.x for i times (default 1), return average time (ns)
rt.vars s       return dictionary with a copy of global variables
                s~"" for all variables, "f" functions, "v" non-functions

Documentation

Overview

Package goal provides an API to goal's interpreter.

In order to evaluate code in the goal programming language, first a new context has to be created.

ctx := goal.NewContext()

This context can then be used to Compile some code, and then Run it. It is possible to customize the context by registering new unary and binary operators using the RegisterMonad and RegisterDyad methods.

See tests in context_test.go, as well as cmd/goal/main.go, for usage examples.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func B2F added in v0.10.0

func B2F(b bool) float64

b2i converts a boolean to a float.

func B2I added in v0.10.0

func B2I(b bool) int64

B2I converts a boolean to an integer.

Types

type AB

type AB struct {
	// contains filtered or unexported fields
}

AB represents an array of booleans, that is an array of zeros (false) and ones (true).

func (*AB) Append added in v0.6.0

func (x *AB) Append(ctx *Context, dst []byte) []byte

Append appends a unique program representation of the value to dst, and returns the extended buffer.

func (*AB) At

func (x *AB) At(i int) bool

At returns array value at the given index.

func (*AB) CloneWithRC added in v0.2.0

func (x *AB) CloneWithRC(rc *int) Value

CloneWithRC satisfies the specification of the RefCounter interface.

func (*AB) DecrRC

func (x *AB) DecrRC()

DecrRC decrements the reference count by one, or zero if it is already non positive.

func (*AB) IncrRC

func (x *AB) IncrRC()

IncrRC increments the reference count by one. It can panic if the value's refcount pointer has not been properly initialized.

func (*AB) InitWithRC added in v0.2.0

func (x *AB) InitWithRC(rc *int)

InitWithRC satisfies the specification of the RefCounter interface.

func (*AB) Len

func (x *AB) Len() int

Len returns the length of the array.

func (*AB) Less added in v0.4.0

func (x *AB) Less(i, j int) bool

Less satisfies the specification of sort.Interface.

func (*AB) LessT added in v0.10.0

func (x *AB) LessT(y Value) bool

LessT satisfies the specification of the Value interface.

func (*AB) Matches

func (x *AB) Matches(y Value) bool

Matches returns true if the two values match like in x~y.

func (*AB) RC added in v0.2.0

func (x *AB) RC() *int

RC returns the array's reference count pointer.

func (*AB) Slice

func (x *AB) Slice() []bool

Slice returns the underlying immutable slice of values. It should not be modified unless the value's refcount pointer is reusable, and even then, you should normally return a new array with the modified slice.

func (*AB) Swap added in v0.9.0

func (x *AB) Swap(i, j int)

Swap satisfies the specification of sort.Interface.

func (*AB) Type

func (x *AB) Type() string

Type returns the name of the value's type.

type AF

type AF struct {
	// contains filtered or unexported fields
}

AF represents an array of reals.

func (*AF) Append added in v0.6.0

func (x *AF) Append(ctx *Context, dst []byte) []byte

Append appends a unique program representation of the value to dst, and returns the extended buffer.

func (*AF) At

func (x *AF) At(i int) float64

At returns array value at the given index.

func (*AF) CloneWithRC added in v0.2.0

func (x *AF) CloneWithRC(rc *int) Value

CloneWithRC satisfies the specification of the RefCounter interface.

func (*AF) DecrRC

func (x *AF) DecrRC()

DecrRC decrements the reference count by one, or zero if it is already non positive.

func (*AF) IncrRC

func (x *AF) IncrRC()

IncrRC increments the reference count by one. It can panic if the value's refcount pointer has not been properly initialized.

func (*AF) InitWithRC added in v0.2.0

func (x *AF) InitWithRC(rc *int)

InitWithRC satisfies the specification of the RefCounter interface.

func (*AF) Len

func (x *AF) Len() int

Len returns the length of the array.

func (*AF) Less added in v0.4.0

func (x *AF) Less(i, j int) bool

Less satisfies the specification of sort.Interface.

func (*AF) LessT added in v0.10.0

func (x *AF) LessT(y Value) bool

LessT satisfies the specification of the Value interface.

func (*AF) Matches

func (x *AF) Matches(y Value) bool

Matches returns true if the two values match like in x~y.

func (*AF) RC added in v0.2.0

func (x *AF) RC() *int

RC returns the array's reference count pointer.

func (*AF) Slice

func (x *AF) Slice() []float64

Slice returns the underlying immutable slice of values. It should not be modified unless the value's refcount pointer is reusable, and even then, you should normally return a new array with the modified slice.

func (*AF) Swap added in v0.9.0

func (x *AF) Swap(i, j int)

Swap satisfies the specification of sort.Interface.

func (*AF) Type

func (x *AF) Type() string

Type returns the name of the value's type.

type AI

type AI struct {
	// contains filtered or unexported fields
}

AI represents an array of integers.

func (*AI) Append added in v0.6.0

func (x *AI) Append(ctx *Context, dst []byte) []byte

Append appends a unique program representation of the value to dst, and returns the extended buffer.

func (*AI) At

func (x *AI) At(i int) int64

At returns array value at the given index.

func (*AI) CloneWithRC added in v0.2.0

func (x *AI) CloneWithRC(rc *int) Value

CloneWithRC satisfies the specification of the RefCounter interface.

func (*AI) DecrRC

func (x *AI) DecrRC()

DecrRC decrements the reference count by one, or zero if it is already non positive.

func (*AI) IncrRC

func (x *AI) IncrRC()

IncrRC increments the reference count by one. It can panic if the value's refcount pointer has not been properly initialized.

func (*AI) InitWithRC added in v0.2.0

func (x *AI) InitWithRC(rc *int)

InitWithRC satisfies the specification of the RefCounter interface.

func (*AI) Len

func (x *AI) Len() int

Len returns the length of the array.

func (*AI) Less added in v0.4.0

func (x *AI) Less(i, j int) bool

Less satisfies the specification of sort.Interface.

func (*AI) LessT added in v0.10.0

func (x *AI) LessT(y Value) bool

LessT satisfies the specification of the Value interface.

func (*AI) Matches

func (x *AI) Matches(y Value) bool

Matches returns true if the two values match like in x~y.

func (*AI) RC added in v0.2.0

func (x *AI) RC() *int

RC returns the array's reference count pointer.

func (*AI) Slice

func (x *AI) Slice() []int64

Slice returns the underlying immutable slice of values. It should not be modified unless the value's refcount pointer is reusable, and even then, you should normally return a new array with the modified slice.

func (*AI) Swap added in v0.9.0

func (x *AI) Swap(i, j int)

Swap satisfies the specification of sort.Interface.

func (*AI) Type

func (x *AI) Type() string

Type returns the name of the value's type.

type AS

type AS struct {
	// contains filtered or unexported fields
}

AS represents an array of strings.

func (*AS) Append added in v0.6.0

func (x *AS) Append(ctx *Context, dst []byte) []byte

Append appends a unique program representation of the value to dst, and returns the extended buffer.

func (*AS) At

func (x *AS) At(i int) string

At returns array value at the given index.

func (*AS) CloneWithRC added in v0.2.0

func (x *AS) CloneWithRC(rc *int) Value

CloneWithRC satisfies the specification of the RefCounter interface.

func (*AS) DecrRC

func (x *AS) DecrRC()

DecrRC decrements the reference count by one, or zero if it is already non positive.

func (*AS) IncrRC

func (x *AS) IncrRC()

IncrRC increments the reference count by one. It can panic if the value's refcount pointer has not been properly initialized.

func (*AS) InitWithRC added in v0.2.0

func (x *AS) InitWithRC(rc *int)

InitWithRC satisfies the specification of the RefCounter interface.

func (*AS) Len

func (x *AS) Len() int

Len returns the length of the array.

func (*AS) Less added in v0.4.0

func (x *AS) Less(i, j int) bool

Less satisfies the specification of sort.Interface.

func (*AS) LessT added in v0.10.0

func (x *AS) LessT(y Value) bool

LessT satisfies the specification of the Value interface.

func (*AS) Matches

func (x *AS) Matches(y Value) bool

Matches returns true if the two values match like in x~y.

func (*AS) RC added in v0.2.0

func (x *AS) RC() *int

RC returns the array's reference count pointer.

func (*AS) Slice

func (x *AS) Slice() []string

Slice returns the underlying immutable slice of values. It should not be modified unless the value's refcount pointer is reusable, and even then, you should normally return a new array with the modified slice.

func (*AS) Swap added in v0.9.0

func (x *AS) Swap(i, j int)

Swap satisfies the specification of sort.Interface.

func (*AS) Type

func (x *AS) Type() string

Type returns the name of the value's type.

type AV

type AV struct {
	// contains filtered or unexported fields
}

AV represents a generic array.

func (*AV) Append added in v0.6.0

func (x *AV) Append(ctx *Context, dst []byte) []byte

Append appends a unique program representation of the value to dst, and returns the extended buffer.

func (*AV) At

func (x *AV) At(i int) V

At returns array value at the given index.

func (*AV) CloneWithRC added in v0.2.0

func (x *AV) CloneWithRC(rc *int) Value

CloneWithRC satisfies the specification of the RefCounter interface.

func (*AV) DecrRC

func (x *AV) DecrRC()

DecrRC decrements the reference count by one, or zero if it is already non positive.

func (*AV) IncrRC

func (x *AV) IncrRC()

IncrRC increments the reference count by one. It can panic if the value's refcount pointer has not been properly initialized.

func (*AV) InitWithRC added in v0.2.0

func (x *AV) InitWithRC(rc *int)

InitWithRC satisfies the specification of the RefCounter interface.

func (*AV) Len

func (x *AV) Len() int

Len returns the length of the array.

func (*AV) Less added in v0.4.0

func (x *AV) Less(i, j int) bool

Less satisfies the specification of sort.Interface.

func (*AV) LessT added in v0.10.0

func (x *AV) LessT(y Value) bool

LessT satisfies the specification of the Value interface.

func (*AV) Matches

func (x *AV) Matches(y Value) bool

Matches returns true if the two values match like in x~y.

func (*AV) RC added in v0.2.0

func (x *AV) RC() *int

RC returns the array's reference count pointer.

func (*AV) Slice

func (x *AV) Slice() []V

Slice returns the underlying immutable slice of values. It should not be modified unless the value's refcount pointer is reusable, and even then, you should normally return a new array with the modified slice.

func (*AV) Swap added in v0.9.0

func (x *AV) Swap(i, j int)

Swap satisfies the specification of sort.Interface.

func (*AV) Type

func (x *AV) Type() string

Type returns the name of the value's type.

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context holds the state of the interpreter.

func NewContext

func NewContext() *Context

NewContext returns a new context for compiling and interpreting code.

func (*Context) Apply

func (ctx *Context) Apply(x, y V) V

Apply calls a value with a single argument.

func (*Context) Apply2

func (ctx *Context) Apply2(x, y, z V) V

Apply2 calls a value with two arguments.

func (*Context) ApplyN

func (ctx *Context) ApplyN(x V, args []V) V

ApplyN calls a value with one or more arguments. The arguments should be provided in stack order, as in the right to left semantics used by the language: the first argument is the last element.

func (*Context) AssignGlobal

func (ctx *Context) AssignGlobal(name string, x V)

AssignGlobal assigns a value to a global variable name.

func (*Context) AssignedLast

func (ctx *Context) AssignedLast() bool

AssignedLast returns true if the last compiled expression was an assignment.

func (*Context) Compile

func (ctx *Context) Compile(loc string, s string) error

Compile parses and compiles code from the given source string. The loc argument is the location used for error reporting and represents, usually a filename.

func (*Context) Eval

func (ctx *Context) Eval(s string) (V, error)

Eval calls Compile with the given string and an empty location, and then Run. You cannot call it within a variadic function, as the evaluation is done on the current context, so it would interrupt compilation of current file. Use EvalPackage for that.

func (*Context) EvalPackage

func (ctx *Context) EvalPackage(s, loc, pfx string) (V, error)

EvalPackage calls Compile with the string s as source, loc as error location (used for caching too, usually a filename), pfx as prefix for global variables (usually a filename without the extension), and then Run. If a package with same location has already been evaluated, it returns ErrPackageImported. This means that even though Goal allows to evaluate (also via import) with the same location several times (which can be useful if separate files using the same package can be used together or alone), only the first one counts. The package is evaluated in a derived context that is then merged on successful completion, so this function can be called within a variadic function.

func (*Context) GetGlobal

func (ctx *Context) GetGlobal(name string) (V, bool)

GetGlobal returns the value attached to a global variable with the given name.

func (*Context) GetVariadic added in v0.10.0

func (ctx *Context) GetVariadic(name string) (V, VariadicFun)

GetVariadic returns the variadic value registered with a given keyword or symbol, along its associated variadic function. It returns a zero value and nil function if there is no registered variadic with such name.

func (*Context) RegisterDyad

func (ctx *Context) RegisterDyad(name string, vf VariadicFun) V

RegisterDyad adds a variadic function to the context, and generates a new dyadic keyword for that variadic (parsing will search for a left argument). The variadic is also returned as a value.

func (*Context) RegisterMonad

func (ctx *Context) RegisterMonad(name string, vf VariadicFun) V

RegisterMonad adds a variadic function to the context, and generates a new monadic keyword for that variadic (parsing will not search for a left argument). The variadic is also returned as a value. Note that while that a keyword defined in such a way will not take a left argument, it is still possible to pass several arguments to it with bracket indexing, like for any value.

func (*Context) Run

func (ctx *Context) Run() (V, error)

Run runs compiled code, if not already done, and returns the result value.

func (*Context) Show

func (ctx *Context) Show() string

Show returns a string representation with debug information about the context.

type Dict added in v0.5.0

type Dict struct {
	// contains filtered or unexported fields
}

Dict represents a dictionary.

func (*Dict) Append added in v0.6.0

func (d *Dict) Append(ctx *Context, dst []byte) []byte

Append appends a unique program representation of the value to dst, and returns the extended buffer.

func (*Dict) CloneWithRC added in v0.5.0

func (d *Dict) CloneWithRC(rc *int) Value

CloneWithRC satisfies the specification of the RefCounter interface.

func (*Dict) DecrRC added in v0.5.0

func (d *Dict) DecrRC()

DecrRC decrements the reference count of both the key and value arrays by one, or zero if they are already non positive.

func (*Dict) IncrRC added in v0.5.0

func (d *Dict) IncrRC()

IncrRC increments the reference count of both the key and value arrays by one.

func (*Dict) InitWithRC added in v0.5.0

func (d *Dict) InitWithRC(rc *int)

InitWithRC satisfies the specification of the RefCounter interface.

func (*Dict) Keys added in v0.5.0

func (d *Dict) Keys() V

Keys returns the keys of the dictionary.

func (*Dict) Len added in v0.5.0

func (d *Dict) Len() int

Len returns the length of the dictionary, that is the common length to its key and value arrays.

func (*Dict) Less added in v0.5.0

func (x *Dict) Less(i, j int) bool

Less satisfies the specification of sort.Interface.

func (*Dict) LessT added in v0.10.0

func (d *Dict) LessT(y Value) bool

LessT satisfies the specification of the Value interface.

func (*Dict) Matches added in v0.5.0

func (d *Dict) Matches(y Value) bool

Matches returns true if the two values match like in x~y.

func (*Dict) Swap added in v0.9.0

func (x *Dict) Swap(i, j int)

Swap satisfies the specification of sort.Interface.

func (*Dict) Type added in v0.5.0

func (d *Dict) Type() string

Type returns the name of the value's type.

func (*Dict) Values added in v0.5.0

func (d *Dict) Values() V

Values returns the values of the dictionary.

type ErrPackageImported

type ErrPackageImported struct{}

ErrPackageImported is returned by EvalPackage for packages that have already been processed (same location).

func (ErrPackageImported) Error

func (e ErrPackageImported) Error() string

type IdentType added in v0.10.0

type IdentType int

IdentType represents the different kinds of special roles for alphanumeric identifiers that act as keywords.

const (
	IdentVar   IdentType = iota // a normal identifier (default zero value)
	IdentMonad                  // a builtin monad (cannot have left argument)
	IdentDyad                   // a builtin dyad (can have left argument)
)

These constants represent the different kinds of special names.

type PanicError

type PanicError struct {
	Msg string // error message (without location)
	// contains filtered or unexported fields
}

PanicError represents a fatal error returned by any Context method.

func (*PanicError) Error

func (e *PanicError) Error() string

Error returns the default string representation. It makes uses of position information obtained from its running context.

type RefCountHolder added in v0.2.0

type RefCountHolder interface {
	RefCounter

	// RC returns the value's root reference count pointer.
	RC() *int
}

RefCountHolder is a RefCounter that has a root refcount pointer. When such values are returned from a variadic function, if the refcount pointer is still nil, InitWithRC is automatically called with a newly allocated refcount pointer to a zero count.

type RefCounter

type RefCounter interface {
	Value

	// IncrRC increments the reference count by one. It can panic if the
	// value's refcount pointer has not been properly initialized.
	IncrRC()

	// DecrRC decrements the reference count by one, or zero if it is
	// already non positive.
	DecrRC()

	// InitWithRC recursively sets the refcount pointer for reusable
	// values, and increments by 2 the refcount of non-reusable values, to
	// ensure immutability of non-reusable children without cloning them.
	InitWithRC(rc *int)

	// CloneWithRC returns a clone of the value, with rc as new refcount
	// pointer.  If the current value's refcount pointer is nil, reusable
	// or equal to the passed one, the same value is returned after
	// updating the refcount pointer as needed, instead of doing a full
	// clone.
	CloneWithRC(rc *int) Value
}

RefCounter is implemented by values that use a reference count. In goal the refcount is not used for memory management, but only for optimization of memory allocations. Refcount is increased by each assignement, and each push operation on the stack, except for pushes corresponding to the last use of a variable (as approximated conservatively). It is reduced after each drop. If refcount is equal or less than one, then the value is considered reusable.

When defining a new type implementing the Value interface, it is only necessary to also implement RefCounter if the type definition makes use of a type implementing it (for example an array type or a generic V).

type S

type S string

S represents (immutable) strings of bytes.

func (S) Append added in v0.6.0

func (s S) Append(ctx *Context, dst []byte) []byte

Append appends a unique program representation of the value to dst, and returns the extended buffer.

func (S) LessT added in v0.10.0

func (s S) LessT(y Value) bool

LessT satisfies the specification of the Value interface.

func (S) Matches

func (s S) Matches(y Value) bool

func (S) Type

func (s S) Type() string

Type retuns "s" for string atoms.

type Scanner

type Scanner struct {
	// contains filtered or unexported fields
}

Scanner represents the state of the scanner.

func NewScanner

func NewScanner(names map[string]IdentType, source string) *Scanner

NewScanner returns a scanner for the given source string.

func (*Scanner) Next

func (s *Scanner) Next() Token

Next produces the next token from the input reader.

type Token

type Token struct {
	Type TokenType // token type
	Pos  int       // token's offset in the source
	Text string    // content text (identifier, string, number)
}

Token represents a token information.

func (Token) String

func (t Token) String() string

type TokenType

type TokenType int

TokenType represents the different kinds of tokens.

const (
	NONE TokenType = iota
	EOF
	ERROR
	ADVERB
	DYAD
	DYADASSIGN
	IDENT
	LEFTBRACE
	LEFTBRACKET
	LEFTBRACKETS
	LEFTPAREN
	NEWLINE
	NUMBER
	MONAD
	REGEXP
	RIGHTBRACE
	RIGHTBRACKET
	RIGHTPAREN
	SEMICOLON
	SADVERB
	STRING
	QQSTART
	QQEND
)

These constants describe the possible kinds of tokens.

func (TokenType) String

func (i TokenType) String() string

type V

type V struct {
	// contains filtered or unexported fields
}

V contains a boxed or unboxed value.

func Canonical

func Canonical(x V) V

Canonical returns the canonical form of a given value, that is the most specialized form, assuming it's already canonical at depth > 1. In practice, if the value is a generic array, but a more specialized version could represent the value, it returns the specialized value. All variadic functions have to return results in canonical form, so this function can be used to ensure that when defining new ones.

func CanonicalRec added in v0.2.0

func CanonicalRec(x V) V

CanonicalRec returns the canonical form of a given value, that is the most specialized form. In practice, if the value is a generic array, but a more specialized version could represent the value, it returns the specialized value. All variadic functions have to return results in canonical form, so this function can be used to ensure that when defining new ones.

func Errorf

func Errorf(format string, a ...interface{}) V

Errorf returns a formatted recoverable error value.

func NewAB

func NewAB(x []bool) V

NewAB returns a new boolean array. It does not initialize the reference counter.

func NewABWithRC added in v0.2.0

func NewABWithRC(x []bool, rc *int) V

NewABWithRC returns a new boolean array.

func NewAF

func NewAF(x []float64) V

NewAF returns a new array of reals. It does not initialize the reference counter.

func NewAFWithRC added in v0.2.0

func NewAFWithRC(x []float64, rc *int) V

NewAFWithRC returns a new array of reals.

func NewAI

func NewAI(x []int64) V

NewAI returns a new int array. It does not initialize the reference counter.

func NewAIWithRC added in v0.2.0

func NewAIWithRC(x []int64, rc *int) V

NewAIWithRC returns a new int array.

func NewAS

func NewAS(x []string) V

NewAS returns a new array of strings. It does not initialize the reference counter.

func NewASWithRC added in v0.2.0

func NewASWithRC(x []string, rc *int) V

NewASWithRC returns a new array of strings.

func NewAV

func NewAV(x []V) V

NewAV returns a new generic array. It does not initialize the reference counter.

func NewAVWithRC added in v0.2.0

func NewAVWithRC(x []V, rc *int) V

NewAVWithRC returns a new generic array.

func NewDict added in v0.5.0

func NewDict(keys, values V) V

NewDict returns a dictionary. Both keys and values should be arrays, and they should have the same length.

func NewError

func NewError(x V) V

NewError returns a new recoverable error value.

func NewF

func NewF(f float64) V

NewF returns a new float64 value.

func NewI

func NewI(i int64) V

NewI returns a new int64 value.

func NewPanic

func NewPanic(s string) V

NewPanic returns a fatal error value.

func NewS

func NewS(s string) V

NewS returns a new string value.

func NewV

func NewV(xv Value) V

NewV returns a new boxed value.

func Panicf

func Panicf(format string, a ...interface{}) V

Panicf returns a formatted fatal error value.

func (V) Append added in v0.6.0

func (v V) Append(ctx *Context, dst []byte) []byte

Append appends a unique program representation of the value to dst, and returns the extended buffer.

func (V) Clone added in v0.2.0

func (x V) Clone() V

Clone creates an identical deep copy of a value, or the value itself if it is reusable. It initializes refcount if necessary.

func (V) CloneWithRC added in v0.2.0

func (x V) CloneWithRC(rc *int) V

CloneWithRC clones the given value using its CloneWithRC method, if it is a RefCounter, or returns it as-is otherwise for immutable values that do not need cloning.

func (V) DecrRC

func (x V) DecrRC()

DecrRC decrements the value reference count (if it has any).

func (V) Error

func (x V) Error() V

Error retrieves the error value. It assumes x.IsError().

func (V) F

func (x V) F() float64

F retrieves the unboxed float64 value. It assumes x.IsF().

func (V) HasRC added in v0.2.0

func (x V) HasRC() bool

HasRC returns true if the value is boxed and implements RefCounter.

func (V) I

func (x V) I() int64

I retrieves the unboxed integer value from N field. It assumes x.IsI().

func (V) IncrRC

func (x V) IncrRC()

IncrRC increments the value reference count (if it has any).

func (V) InitRC added in v0.2.0

func (x V) InitRC()

InitRC initializes refcount if the value is a RefCountHolder with nil refcount.

func (V) InitWithRC added in v0.2.0

func (x V) InitWithRC(rc *int)

InitWithRC calls the method of the same name on boxed values.

func (V) IsCallable added in v0.10.0

func (x V) IsCallable() bool

IsCallable returns true if the value can be called with one or more arguments. This is true for functions, arrays, strings and regexps, for example.

func (V) IsError

func (x V) IsError() bool

IsError returns true if the value is a recoverable error.

func (V) IsF

func (x V) IsF() bool

IsF returns true if the value is a float.

func (V) IsFalse added in v0.10.0

func (x V) IsFalse() bool

IsFalse returns true for false values, that is zero numbers, empty strings, zero-length values, and errors.

func (V) IsFunction

func (x V) IsFunction() bool

IsFunction returns true if the value is some kind of function.

func (V) IsI

func (x V) IsI() bool

IsI returns true if the value is an integer.

func (V) IsPanic

func (x V) IsPanic() bool

IsPanic returns true if the value is a fatal error.

func (V) IsTrue added in v0.10.0

func (x V) IsTrue() bool

IsTrue returns true for true values, that is non-zero numbers, non-empty strings, and non-zero length values that are not errors.

func (V) IsValue

func (x V) IsValue() bool

IsValue returns true if the value is a boxed value satisfying the Value interface. You can then get the value with the Value method.

func (V) Len added in v0.10.0

func (x V) Len() int

Len returns the length of a value like in #x.

func (V) LessT added in v0.10.0

func (x V) LessT(y V) bool

LessT returns true if x is ordered before y. It represents a strict total order (except non-strict for NaNs). Values are ordered as follows: unboxed atoms first (numbers, variadics, then lambdas), then boxed values. Otherwise, values are compared with < and > when comparable, and otherwise using their Type string value. As a special case, comparable arrays are compared first by length, or lexicographically if they are of equal length.

func (V) Matches added in v0.10.0

func (x V) Matches(y V) bool

Matches returns true if the two values match like in x~y.

func (V) Panic added in v0.6.0

func (x V) Panic() string

Panic returns the panic string. It assumes x.IsPanic().

func (V) Rank

func (x V) Rank(ctx *Context) int

Rank returns the default rank of the value, that is the number of arguments it normally takes. It returns 0 for non-function values. This default rank is used when a function is used in an adverbial expression that has different semantics depending on the function arity. Currently, ranks are as follows:

variadic	2
lambda		number of arguments
projections	number of gaps
derived verb	1

func (V) Sprint

func (v V) Sprint(ctx *Context) string

Sprint returns a matching program string representation of the value.

func (V) Type

func (x V) Type() string

Type returns the name of the value's type.

func (V) Value

func (x V) Value() Value

Value retrieves the boxed value, or nil if the value is not boxed. You can check whether the value is boxed with IsValue(v).

type Value

type Value interface {
	// Matches returns true if the value matches another (in the sense of
	// the ~ operator).
	Matches(Value) bool
	// Append appends a unique program representation of the value to dst,
	// and returns the extended buffer. It should not store the returned
	// buffer elsewhere, so that it's possible to safely convert it to
	// string without allocations.
	Append(ctx *Context, dst []byte) []byte
	// Type returns the name of the value's type. It may be used by LessT to
	// sort non-comparable values using lexicographic order.  This means
	// Type should return different values for non-comparable values.
	Type() string
	// LessT returns true if the value should be orderer before the given
	// one. It is used for sorting values, but not for element-wise
	// comparison with < and >. It should produce a strict total order,
	// that is, irreflexive (~x<x), asymmetric (if x<y then ~y<x),
	// transitive, connected (different values are comparable, except
	// NaNs).
	LessT(Value) bool
}

Value is the interface satisfied by all boxed values.

type VariadicFun

type VariadicFun func(*Context, []V) V

VariadicFun represents a variadic function. The array of arguments is in stack order: the first argument is its last element.

Directories

Path Synopsis
cmd
Package cmd provides a quick way to create derived interpreters.
Package cmd provides a quick way to create derived interpreters.
Package os provides variadic function definitions for IO/OS builtins.
Package os provides variadic function definitions for IO/OS builtins.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL