government / eval / lists.go

@ acb25bc2dcb663eb679fb19123bf0471f5c3c349 | history


package eval

import (
	"strings"
	"unicode/utf8"

	"government/sexpr"
)

func cons(args []sexpr.Value) (sexpr.Value, error) {
	return sexpr.Cons(args[0], args[1]), nil
}

func car(args []sexpr.Value) (sexpr.Value, error) {
	p, ok := args[0].(*sexpr.Pair)
	if !ok {
		return nil, errorf(ErrType, "car needs a pair, got %s", sexpr.Print(args[0]))
	}
	return p.Car, nil
}

func cdr(args []sexpr.Value) (sexpr.Value, error) {
	p, ok := args[0].(*sexpr.Pair)
	if !ok {
		return nil, errorf(ErrType, "cdr needs a pair, got %s", sexpr.Print(args[0]))
	}
	return p.Cdr, nil
}

// strlen counts code points, so (strlen "héllo") is 5 although the UTF-8
// encoding is 6 bytes.
func strlen(args []sexpr.Value) (sexpr.Value, error) {
	s, ok := args[0].(sexpr.String)
	if !ok {
		return nil, errorf(ErrType, "argument 1 of strlen must be a string, got %s", sexpr.Print(args[0]))
	}
	return sexpr.Int(utf8.RuneCountInString(string(s))), nil
}

func strcat(args []sexpr.Value) (sexpr.Value, error) {
	var b strings.Builder
	for i, a := range args {
		s, ok := a.(sexpr.String)
		if !ok {
			return nil, errorf(ErrType, "argument %d of strcat must be a string, got %s", i+1, sexpr.Print(a))
		}
		b.WriteString(string(s))
	}
	return sexpr.String(b.String()), nil
}

func isString(args []sexpr.Value) (sexpr.Value, error) {
	_, ok := args[0].(sexpr.String)
	return sexpr.Bool(ok), nil
}