cue-lang / docs-and-content

A place to discuss, plan, and track documentation on cuelang.org
5 stars 1 forks source link

docs/howto/produce-string-set-from-list: Producing a set of strings from a list #105

Closed NoamTD closed 5 months ago

NoamTD commented 6 months ago

A howto guide that explains how to product a set of strings from a list - sorted and with duplicate elements removed.

exec cue vet file.cue
-- file.cue --
import (
    "strings"
    "list"
)

stringList: ["d", "a", "b", "a", "c", "b", "b"]

stringSet: {
    _map: { for s in stringList { (s): _ } }
    list.SortStrings([for s, _ in _map {s}])
}

stringSet: ["a", "b", "c", "d"]
NoamTD commented 6 months ago

@jpluscplusm FYI - please let me know if there's a convention I should be aware of for opening issues here

jpluscplusm commented 6 months ago

@NoamTD Thanks for opening this issue!

I've slightly amended the title:

Please add a txtar repro containing the technique that this guide will demonstrate, and then we can mark this issue as ready to be picked up.

TVM!

NoamTD commented 6 months ago

@jpluscplusm thanks for clarifying about the naming - makes a lot of sense

I added a txtar - please let me know if it's clear. In the example I added an explicit stringSet list (in addition to the comprehension) to "prove" that the transformation works, but I'm wondering if it's preferable to just show the output (with cue export -e)

jpluscplusm commented 5 months ago

I reckon the output proves the transformation sufficiently. I think there's a place for using unification to assert the equivalence of generated and statically stated fields, but I don't think it's needed here.

If we use cue eval then we get the advantage of a single line for each output list and don't need to shrink the number of output lines by using -e. Also, how about using a let declaration rather than a hidden field? Because of https://github.com/cue-lang/cue/issues/2986 it needs to be separate from the comprehension, but I think this looks pretty decent:

exec cue export
-- file.cue --
package example

stringList: ["d", "a", "b", "a", "c", "b", "b"]

stringSet: {
    let map = {for a in stringList {(a): _}}
    [for b, _ in map {b}]
}

This also drops the list sorting, which feels like it generalises the solution in a positive fashion.

jpluscplusm commented 5 months ago

I think this should be a Commented CUE howto with some short intro prose followed by a 2-pane, left-right file.cue/cue eval code block. There might be some related content it could link to, but I'm ambivalent about what makes sense for that.

I'll mark this as Ready 👍. Thanks, @NoamTD!

jpluscplusm commented 5 months ago

Closed via https://github.com/cue-lang/cuelang.org/commit/11094806ff902554f50fd7928d64e5a3039711d8.

Thanks, @NoamTD 🎉