Documentation ¶
Overview ¶
Package trealla provides a Prolog interpreter. Powered by Trealla Prolog running under WebAssembly.
Example ¶
package main import ( "context" "fmt" "github.com/trealla-prolog/go/trealla" ) func main() { ctx := context.Background() // create a new Prolog interpreter pl, err := trealla.New() if err != nil { panic(err) } // start a new query query := pl.Query(ctx, "member(X, [1, foo(bar), c]).") // calling Close is not necessary if you iterate through the whole query, but it doesn't hurt defer query.Close() // iterate through answers for query.Next(ctx) { answer := query.Current() x := answer.Solution["X"] fmt.Println(x) } // make sure to check the query for errors if err := query.Err(); err != nil { panic(err) } }
Output: 1 foo(bar) c
Example (Register) ¶
ctx := context.Background() pl, err := New() if err != nil { panic(err) } // Let's add a base32 encoding predicate. // To keep it brief, this only handles one mode. // base32(+Input, -Output) is det. pl.Register(ctx, "base32", 2, func(_ Prolog, _ Subquery, goal0 Term) Term { // goal is the goal called by Prolog, such as: base32("hello", X). // Guaranteed to match up with the registered arity and name. goal := goal0.(Compound) // Check the Input argument's type, must be string. input, ok := goal.Args[0].(string) if !ok { // throw(error(type_error(list, X), base32/2)). return Atom("throw").Of(Atom("error").Of( Atom("type_error").Of("list", goal.Args[0]), Atom("/").Of(Atom("base32"), 2), )) } // Check Output type, must be string or var. switch goal.Args[1].(type) { case string: // ok case Variable: // ok default: // throw(error(type_error(list, X), base32/2)). return Atom("throw").Of(Atom("error").Of( Atom("type_error").Of("list", goal.Args[0]), Atom("/").Of(Atom("base32"), 2), )) } // Do the encoding actual work. output := base32.StdEncoding.EncodeToString([]byte(input)) // Return a goal that Trealla will unify with its input: // base32(Input, "output_goes_here"). return Atom("base32").Of(input, output) }) // Try it out. answer, err := pl.QueryOnce(ctx, `base32("hello", Encoded).`) if err != nil { panic(err) } fmt.Println(answer.Solution["Encoded"])
Output: NBSWY3DP
Index ¶
- func IsFailure(err error) bool
- func Marshal(term Term) (string, error)
- type Answer
- type Atom
- type Compound
- type ErrFailure
- type ErrThrow
- type Option
- func WithDebugLog(logger *log.Logger) Option
- func WithLibraryPath(path string) Option
- func WithMapDir(alias, dir string) Option
- func WithPreopenDir(dir string) Option
- func WithQuiet() Option
- func WithStderrLog(logger *log.Logger) Option
- func WithStdoutLog(logger *log.Logger) Option
- func WithTrace() Option
- type Predicate
- type Prolog
- type Query
- type QueryOption
- type Subquery
- type Substitution
- type Term
- type Variable
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Answer ¶
type Answer struct { // Query is the original query goal. Query string // Solution (substitutions) for a successful query. // Indexed by variable name. Solution Substitution `json:"answer"` // Stdout is captured standard output text from this query. Stdout string // Stderr is captured standard error text from this query. Stderr string }
Answer is a query result.
type Atom ¶ added in v0.0.10
type Atom string
Atom is a Prolog atom.
func (Atom) Indicator ¶ added in v0.0.10
Indicator returns a predicate indicator for this atom ("foo/0").
func (Atom) Of ¶ added in v0.0.10
Of returns a Compound term with this atom as the principal functor.
func (*Atom) UnmarshalJSON ¶ added in v0.0.10
type Compound ¶
type Compound struct { // Functor is the principal functor of the compound. // Example: the Functor of foo(bar) is "foo". Functor Atom // Args are the arguments of the compound. Args []Term }
Compound is a Prolog compound type.
type ErrFailure ¶ added in v0.0.10
type ErrFailure struct { // Query is the original query goal. Query string // Stdout output from the query. Stdout string // Stderr output from the query (useful for traces). Stderr string }
ErrFailure is returned when a query fails (when it finds no solutions).
func (ErrFailure) Error ¶ added in v0.0.10
func (err ErrFailure) Error() string
Error implements the error interface.
type ErrThrow ¶ added in v0.0.10
type ErrThrow struct { // Query is the original query goal. Query string // Ball is the term thrown by throw/1. Ball Term // Stdout output from the query. Stdout string // Stderr output from the query (useful for traces). Stderr string }
ErrThrow is returned when an exception is thrown during a query.
type Option ¶
type Option func(*prolog)
Option is an optional parameter for New.
func WithDebugLog ¶ added in v0.0.10
WithDebugLog writes debug messages to the given logger.
func WithLibraryPath ¶ added in v0.0.10
WithLibraryPath sets the global library path for the interpreter. `use_module(library(foo))` will point to here. Equivalent to Trealla's `--library` flag.
func WithMapDir ¶
WithMapDir sets alias to point to directory dir, granting access to it. This can be called multiple times with different aliases.
func WithPreopenDir ¶
WithPreopenDir sets the preopen directory to dir, granting access to it. Calling this again will overwrite it. More or less equivalent to `WithMapDir(dir, dir)`.
func WithQuiet ¶ added in v0.0.10
func WithQuiet() Option
WithQuiet enables the quiet option. This disables some warning messages.
func WithStderrLog ¶ added in v0.0.10
WithStderrLog sets the standard error logger, writing all stderr input from queries. Note that traces are written to stderr.
func WithStdoutLog ¶ added in v0.0.10
WithStdoutLog sets the standard output logger, writing all stdout input from queries.
type Predicate ¶ added in v0.0.10
Predicate is a Prolog predicate implemented in Go. subquery is an opaque number representing the current query. goal is the goal called, which includes the arguments.
Return value meaning:
- By default, the term returned will be unified with the goal.
- Return a throw/1 compound to throw instead.
- Return a call/1 compound to call a different goal instead.
- Return a 'fail' atom to fail instead.
- Return a 'true' atom to succeed without unifying anything.
type Prolog ¶
type Prolog interface { // Query executes a query. Query(ctx context.Context, query string, options ...QueryOption) Query // QueryOnce executes a query, retrieving a single answer and ignoring others. QueryOnce(ctx context.Context, query string, options ...QueryOption) (Answer, error) // Consult loads a Prolog file with the given path. Consult(ctx context.Context, filename string) error // ConsultText loads Prolog text into module. Use "user" for the global module. ConsultText(ctx context.Context, module string, text string) error // Register a native Go predicate. // NOTE: this is *experimental* and its API will likely change. Register(ctx context.Context, name string, arity int, predicate Predicate) error }
Prolog is a Prolog interpreter.
type Query ¶ added in v0.0.10
type Query interface { // Next computes the next solution. Returns true if it found one and false if there are no more results. Next(context.Context) bool // Current returns the current solution prepared by Next. Current() Answer // Close destroys this query. It is not necessary to call this if you exhaust results via Next. Close() error // Err returns this query's error. Always check this after iterating. Err() error }
Query is a Prolog query iterator.
type QueryOption ¶ added in v0.0.10
type QueryOption func(*query)
QueryOption is an optional parameter for queries.
func WithBind ¶ added in v0.0.10
func WithBind(variable string, value Term) QueryOption
WithBind binds the given variable to the given term. This can be handy for passing data into queries. `WithBind("X", "foo")` is equivalent to prepending `X = "foo",` to the query.
Example ¶
package main import ( "context" "fmt" "github.com/trealla-prolog/go/trealla" ) func main() { ctx := context.Background() pl, err := trealla.New() if err != nil { panic(err) } // bind the variable X to the atom 'hello world' through query options answer, err := pl.QueryOnce(ctx, "write(X).", trealla.WithBind("X", trealla.Atom("hello world"))) if err != nil { panic(err) } fmt.Println(answer.Stdout) }
Output: hello world
func WithBinding ¶ added in v0.0.10
func WithBinding(subs Substitution) QueryOption
WithBinding binds a map of variables to terms. This can be handy for passing data into queries.
type Subquery ¶ added in v0.0.10
type Subquery int32
Subquery is an opaque value representing an in-flight query. It is unique as long as the query is alive, but may be re-used later on.
type Substitution ¶ added in v0.0.10
Substitution is a mapping of variable names to substitutions (terms). For query results, it's one answer to a query. Substitution can also be used to bind variables in queries via WithBinding.
func (Substitution) Scan ¶ added in v0.0.10
func (sub Substitution) Scan(obj any) error
Scan sets any fields in obj that match variables in this substitution. obj must be a pointer to a struct or a map.
Example ¶
ctx := context.Background() pl, err := New() if err != nil { panic(err) } answer, err := pl.QueryOnce(ctx, `X = 123, Y = abc, Z = ["hello", "world"].`) if err != nil { panic(err) } var result struct { X int Y string Hi []string `prolog:"Z"` } if err := answer.Solution.Scan(&result); err != nil { panic(err) } fmt.Printf("%+v", result)
Output: {X:123 Y:abc Hi:[hello world]}
func (Substitution) String ¶ added in v0.0.10
func (sub Substitution) String() string
String returns a Prolog representation of this substitution in the same format as ISO variable_names/1 option for read_term/2.
func (*Substitution) UnmarshalJSON ¶ added in v0.0.10
func (sub *Substitution) UnmarshalJSON(bs []byte) error
UnmarshalJSON implements the encoding/json.Marshaler interface.