Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add uniq() builtin #647

Open
antonmedv opened this issue May 10, 2024 · 2 comments
Open

Add uniq() builtin #647

antonmedv opened this issue May 10, 2024 · 2 comments
Labels

Comments

@antonmedv
Copy link
Member

No description provided.

@jippi
Copy link

jippi commented May 12, 2024

Not sure if usable or not, but I implemented this recently in my own project (source + docs)

I couldn't figure out how to make the input accept cmp.Ordered instead of specific types :)

and inline below

func UniqSlice[T cmp.Ordered](in []T) []T {
	slices.Sort(in)

	return slices.Compact(in)
}

// Uniq takes a list of strings or interface{}, sorts them
// and remove duplicated values
var Uniq = expr.Function(
	"uniq",
	func(args ...any) (any, error) {
		switch elements := args[0].(type) {
		case []any:
			var result []string

			for _, element := range elements {
				result = append(result, fmt.Sprintf("%s", element))
			}

			return UniqSlice(result), nil

		case []string:
			return UniqSlice(elements), nil

		default:
			return nil, fmt.Errorf("invalid input, must be an array of [string] or [interface], got %T", args[0])
		}
	},
	new(func([]any) []string),    // []any -> []string (when using map() that always return []any)
	new(func([]string) []string), // []string -> []string
)

@antonmedv
Copy link
Member Author

I couldn't figure out how to make the input accept cmp.Ordered instead of specific types :)

This is one of the limitations of our virtual machine. As we use stack of []any, information on type is "lost" (can be retrieved via reflection).

For uniq() builtin to work not only with strings, we need to implement a more general approach, probably implementing in in bytecode or in VM.

Implementing uniq() is much ore tricky 👀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants