[Question]
  [
Given a set of letters, output all strings made of those letters. (This is [Kleene star](https://en.wikipedia.org/wiki/Kleene_star) of the set.) For example, for `{'a','b'}`, the strings are:
```
'', 'a', 'b', 'aa', 'ab', 'ba', 'bb', 'aaa', 'aab', ...
```
**Input:** A non-empty collection of distinct letters `a..z`. These may be characters or single-character strings.
**Output:** All strings in those letters, in any order, without repeats. You may use lists of chars as strings.
This is an infinite list, so you can output it by:
* Running forever writing more and more strings. These strings can be written in any flat separated format, meaning that they you can tell where each string ends, but the strings aren't subdivided into groups.
* Taking a number `n` as input and outputting the first `n` strings in any flat separated format
* Yielding each string in turn from a generator object
* Producing an infinite object
Be sure that your method eventually produces every string in the output, since it's possible to produce infinitely many strings from the set while never getting to some strings.
You may **not** output it by
* Producing the `n`th string given `n`
* Providing a membership oracle that decides if a given string belongs to the set
Built-ins are allowed, but I ask voters to give attention to answers that implement the operation themselves over ones that mostly rely on a built-in.
```
var QUESTION_ID=74273,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/74273/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
  
[Answer]
# Python 2, 53 ~~56~~
-3 after realizing that `yield x` can be used as an expression.
```
def f(s):yield'';[(yield w+c)for w in f(s)for c in s]
```
[Answer]
# Haskell, 24 bytes
```
f s=[]:[b:a|a<-f s,b<-s]
```
Produces an infinite list.
```
*Main> f "abc"
["","a","b","c","aa","ba","ca","ab","bb","cb","ac","bc","cc","aaa","baa","caa","aba","bba","cba",…
```
[Answer]
# Mathematica, ~~32~~ 31 Bytes
```
Do[Echo/@#~Tuples~n,{n,0,∞}]&
```
# Edit:
CatsAreFluffy scraped off one byte.
[Answer]
## JavaScript (ES6), 61 bytes
```
function*g(s){yield'';for(let r of g(s))for(c of s)yield c+r}
```
Port of @feersum's Python generator. The `let` is necessary. Save 2 bytes by using an array comprehension (failed ES7 proposal, but works in Firefox 30-57):
```
function*g(s){yield'';[for(r of g(s))for(c of s)yield c+r]}
```
Alternative version for 73 bytes that returns the first `n` elements yielded by the above generator:
```
(s,n)=>Array(n).fill('').map(g=(r,i)=>i--?g(r+s[i%l],i/l|0):r,l=s.length)
```
[Answer]
# Perl, ~~39~~ ~~37~~ 35 bytes
(First describes an older version. The new shorter program is at the end)
Includes +3 for `-alp`
Run with the set of characters on STDIN, e.g. `perl -alp kleene.pl <<< "a b c"`
`kleene.pl` (this version is 34+3 bytes):
```
$#a=$"=","}for(@a){push@a,<{@F}$_>
```
Add +2 for `-F` (drop implicit `-a` if no spaces between input characters, or -6 (only `@a=""` before `}`) if we already put commas between the characters on STDIN
## Explanation:
The `-alp` options make the code effectively:
```
BEGIN { $/ = "\n"; $\ = "\n"; }
LINE: while (defined($_ = <ARGV>)) {
    chomp $_;
    our @F = split(' ', $_, 0);
    $#a = $" = ',';
}
foreach $_ (@a) {
    use File::Glob ();
    push @a, glob('{' . join($", @F) . '}' . $_);
}
```
As you can see `<>` in perl is not only used for readline, but can also do shell style globbing (in fact in ancient perls it was implemented by calling the shell).
For example `<{a,b}{1,2}>` will expand to `"a1","a2","b1","b2"`
So if we have the elements in `@F` we just need to add commas inbetween. The default inbetween character for interpolation is space, which is stored in special variable `$"`. So setting `$"` to `,` will turn `"{@F}"` into `{a,b}` if `@F=qw(a b)` (globs expand as strings)
In fact I would really have liked to loop with something like `glob"{@F}"x$n++`, but I kept running into the problem that the first empty line doesn't get generated and all workarounds I found made the code too long.
So another essential part of this code is that if you use a `for` to loop over an array you can actually push extra elements on it during the loop and the loop will also pick up these new elements. So if in the loop we are e.g. at element `"ab"`, then `<{@F}$_>` will expand to `<{a,b}ab>` which in list context becomes `("aab", "bab")`. So if I push these on `@a` then the strings extended one to the left become available too
All I still need to do is prime the loop with an empty string. That is done using`$#a = 0` (`,` in numeric context becomes `0`) which causes the first and only element of `@a` to become undef which will behave like `""` when I use it
## Improvement
In fact by doing tests for this explanation I found a short way to use a growing glob that properly handles the first empty entry. Run as `perl -ap kleene0.pl <<< "a b"` (so add 2 bytes for `-ap`)
`kleene0.pl` (this version is 33+2 bytes):
```
$"=",";print<$z,>;$z.="{@F}";redo
```
All these solutions will keep more and more of the output in memory and that will cause the program to fail after some time. You can also use perl globs for lazy generation by using them in scalar context, but that makes the programs longer....
[Answer]
# Pyth, 7
```
<s^LzQQ
```
[Try it here](http://pyth.herokuapp.com/?code=%3Cs%5ELzQQ&input=ab%0A4&debug=0)
This computes the cartesian product of the input with each number from `0..n-1`, joins them, and then only keeps the first `n`. This will time out online for numbers or strings that are much bigger than 3-4.
Alternatively, to get infinite output look at Jakube's [answer](https://codegolf.stackexchange.com/a/74287/31625).
[Answer]
# Jelly, ~~8~~ 6 bytes
```
⁷³p$Ȯ¿
```
[Try it online!](http://jelly.tryitonline.net/#code=4oG3wrNwJMiuwr8&input=&args=YWI)
### How it works
```
⁷³p$Ȯ¿    Monadic link. Argument: A (alphabet)
⁷         Set the return value to '\n'.
     ¿    While loop.
            Condition:
    Ȯ         Print the current return value and return it (always truthy).
            Body:
   $          Combine the two links to the left into a single, monadic link.
 ³              Yield A.
  p             Perform the Cartesian product of A and the current return value,
                updating the return value in the process.
```
## Alternate version, 6 bytes
```
R’ḃL}ị
```
This is a dyadic link that accepts an alphabet and the desired number of strings as left and right arguments, respectively.
[Try it online!](http://jelly.tryitonline.net/#code=UuKAmeG4g0x94buLCsOn4bm-&input=&args=Nw+YWI)
### How it works
```
R’ḃL}ị    Dyadic link. Arguments: n (integer), A (alphabet)
R         Range; yield [1, ..., n].
 ’        Decrement; yield [0, ..., n-1].
   L}     Yield l, the length of A.
  ḃ       Convert every i in [0, ..., n-1] to bijective base l.
     ị    For each array of digits, retrieve the corresponding characters of A.
```
[Answer]
# Python 2, ~~89~~ ~~84~~ 83 bytes
```
x,n=input()
l=len(x)
for i in range(n):
 s=''
 while i:i-=1;s+=x[i%l];i/=l
 print s
```
[Answer]
## CJam, ~~16~~ 10 bytes
*Thanks to jimmy23013 for saving 6 bytes.*
```
N{eam*_o}h
```
Input is one command-line argument per character. Output is one string on each line.
[Try it online!](http://cjam.tryitonline.net/#code=TGF7XzpwO2Vhc20qOnN9aA&input=&args=YWI) (But kill it immediately...)
### Explanation
```
N      e# Push [\n]. At each step this array will contain all strings of length N,
       e# each followed by a linefeed.
{      e# Infinite loop...
  ea   e#   Read command-line arguments.
  m*   e#   Cartesian product: pairs each letter with each string in the list.
  _o   e#   Output all the strings of the current length.
}h
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 2 bytes
```
Ňŧ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FkuOth9dvqQ4KbkYKrBgiVJikhKEDQA)
```
Ňŧ
Ň       Nondeterministically choose an natural number, say n
 ŧ      Nondeterministically choose a tuple of n elements from the input list
```
In the default mode, Nekomata prints all possible outputs.
[Answer]
# Pyth, 7 bytes
```
.V0j^zb
```
Alternative to @fry. 
This program reads a string and keeps on printing strings until infinity. 
### Explanation:
```
.V0      for b in (0 to infinity):
    ^zb     compute all strings of length b consisting of the input alphabet
   j        print each one on a separate line
```
Alternatively the following will also work. A little bit more hacky though. 
```
u
M^zH7
```
[Answer]
# Haskell, 33 bytes
```
k u=do s<-[0..];mapM(\_->u)[1..s]
```
For exampe, `k "xyz"` is the infinite list `["","x","y","z","xx","xy","xz","yx","yy","yz","zx","zy","zz","xxx",...]`
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 10 bytes
```
0cD`G@Z^DT
```
[**Try it online!**](http://matl.tryitonline.net/#code=MGNEYEdAWl5EVA&input=J2FiJw) But don't leave it running for long, to avoid large computational load on the server.
The program displays the strings dynamically, each string on a different line.
```
0cD             % force display of a newline to represent the empty string
   `      T     % infinite do-while loop
    G           % push input, or nothing if no input has been taken yet
     @          % push iteration. Gives 1, 2,... in each iteration
      Z^        % Cartesian power. In the first iteration takes input implicitly 
       D        % display
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~6 7~~ 5 bytes
```
Θṁπ⁰N
```
[Try it online!](https://tio.run/##yygtzv7//9yMhzsbzzc8atzg9////8QkAA "Husk – Try It Online")
## Explanation
```
 ṁ  N map natural numbers to:
  π⁰  cartesian power of input
 ṁ    and join
Θ     prepend empty string
```
[Answer]
# Python 3, 95
```
from itertools import*
def f(x,l=0):
 while 1:print(*combinations_with_replacement(x*l,l));l+=1
```
Why must itertools functions have such long names.
[Answer]
## Ruby, ~~65~~ 60 bytes
```
->a{n=-1;loop{puts a.repeated_permutation(n+=1).map &:join}}
```
Such long builtin names...
[Answer]
# Scala, 69
```
def f[A](s:Set[A]):Stream[List[A]]=Nil#::f(s).flatMap(x=>s.map(_::x))
```
Lazy streams are quite nice for this kind of thing.
[Answer]
# C (gcc), ~~99~~ ~~97~~ ~~95~~ 93 bytes
-2 bytes thanks to @ceilingcat (replaced `putchar(v[~s[i++]])` by `printf(v+~s[i++])`).
-2 more bytes thanks to @ceilingcat (made `i` a pointer rather than an index).
-2 bytes once more, again thanks to ceilingcat (replaced `(*i)--+l` by `--*i==~l`, reversing the last two arguments of the ternary conditional operator, making it possible to remove the parentheses around `*i++=-1`).
```
s[999];*i;f(v,l)int*v;{for(i=s;printf(v+~*i++););for(i=s,puts("");;)--*i==~l?*i++=-1:f(v,l);}
```
[Try it online!](https://tio.run/##LYxLDsIgFEXHsgrCiMcnsc7whbgBd6AOKgbzkto2pTJp2q0jRqfnnHuDfYZQSro4526oCKPMpgPqZ5VxicMkySccpwqq0ZsirQEB/8aM7zlJIQARrFXk/dadvo23zfF3hWupY/5qqZd5oAewhe2iPIvrvr0Lrnlj@AGQreUD)
[Answer]
## [Pyke](https://github.com/muddyfish/PYKE) (commit 31), ~~10~~ 9 bytes
```
=blR.fbtp
```
Explanation:
```
=b         -    set characters for base conversion to eval_or_not(input())
  l        -   len(^)
   R      -  [^, eval_or_not(input()]
    .f    - first_n(^)
      b   -    conv_base(^)
       t  -   ^[-1]
        p -  print(^)
```
[Answer]
# Japt, ~~50~~ ~~40~~ ~~34~~ 28 bytes
```
V²o ®s1+Ul)£UgXnH)¯X¦0}Ãâ ¯V
```
Input is `"string", number of items`. Output is sorted by length, then reverse alphabet order. [Test it online!](http://ethproductions.github.io/japt?v=master&code=VrJvIK5zMStVbCmjVWdYbkgpr1imMH3D4iCvVg==&input=ImFiYyIgNTA=)
### How it works
```
V²  o ®   s1+Ul)£  UgXnH)¯  X¦ 0}Ã â ¯  V
Vp2 o mZ{Zs1+Ul)mX{UgXnH)s0,X!=0}} â s0,V
Vp2 o      // Create the range [0..V²).
mZ{     }  // Map each item Z in this range to:
Zs1+Ul)    //  Take the base-(1+U.length) representation of Z.
mX{     }  //  Map each char X in this to:
XnH        //   Parse X as a base-32 number.
Ug   )     //   Take the char at index -^ in U.
s0,X!=0    //   If X is 0, slice it to an empty string.
â          // Uniquify the result.
s0,V       // Slice to the first V items.
```
This version takes a while if you want to do any more than 100 items. If you want a faster version, [try this 32-byte one](http://ethproductions.github.io/japt?v=master&code=VioyIG8gbXMxK1VsKWZAIVhmJzDDrqNVZ1huSH3Dr1Y=&input=ImFiYyIgNTA=):
```
V*2 o ms1+Ul)f@!Xf'0Ã®£UgXnH}Ã¯V
```
[Answer]
# Cinnamon Gum, 6 bytes
```
0000000: 6801 301c e74b                           h.0..K
```
Non-competing because Cinnamon Gum was made after this challenge.
[Try it online (TIO limits output).](http://cinnamon-gum.tryitonline.net/#code=MDAwMDAwMDogNjgwMSAzMDFjIGU3NGIgICAgICAgICAgICAgICAgICAgICAgICAgICBoLjAuLks&input=ImFiIg)
## Explanation
The `h` puts Cinnamon Gum in *format and generate mode*. The rest of the string decompresses to `[%s]*`. The `%s` is then replaced with the input, and a generator is created that outputs all possible strings matching the regex.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
g<∞*εÅв¦J
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/3eZRxzytc1sPt17YdGiZ1///iUnJAA "05AB1E – Try It Online")
```
g             # length of the input
 <            # - 1
  ∞           # infinite list [1, 2, 3, …]
   *          # multiply each by the length-1
    ε         # for each:
     Åв       #  custom base conversion, using the input as the list of digits
       ¦      #  chop off the first digit
        J     #  join the rest to a string
```
[Answer]
# [R](https://www.r-project.org/), ~~53~~ 50 bytes
-3 bytes thanks to Dominic van Essen
```
r=scan(,s<-"");repeat cat("",s<-outer(s,r,paste0))
```
[Try it online!](https://tio.run/##K/r/v8i2ODkxT0On2EZXSUnTuii1IDWxRCE5sURDSQkkmF9aklqkUaxTpFOQWFySaqCp@T@RK4kr@T8A "R – Try It Online")
Prints the infinite list, separated by spaces.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
∞€ã˜õš
```
[Try it online!](https://tio.run/##ARoA5f9vc2FiaWX//@KInuKCrMOjy5zDtcWh//9hYg "05AB1E – Try It Online")
```
∞        # push a list of all positive integers
 €ã      # take the input to each cartesian power
   ˜     # flatten the resulting list of lists
    õ    # push the empty string
     š   # prepend it to the infinite list of strings
```
Taking a string the 0th cartesian cartesian yields `[[]]`, which would get completely lost when flattening (`˜`), this is why the empty string is prepended manually.  
[`∞<€ã€``](https://tio.run/##yy9OTMpM/f//Ucc8m0dNaw4vBhIJ//8nJgEA) is an alternative 6-byter which uses `[]` to represent the empty string.
[Answer]
# [Curry (KiCS2)](https://www-ps.informatik.uni-kiel.de/kics2/index.html), 18 bytes
```
f s=""?anyOf s:f s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m706ubSoqDI-OzO52GjBgqWlJWm6FpvSFIptlZTsE_Mq_YFMKyCGSKzNTczMU7BVSFNQSkxSgojBNAEA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
ƛ⁰τḢ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLGm+KBsM+E4biiIiwiIiwiMjAwMFxuXCJhYmNcIiJd) Takes the number of strings and the string.
```
ƛ    # For each number in 1...n
 ⁰τ  # Convert to base <string>
   Ḣ # Remove the first character
```
Alternatively, a version that prints infinitely (and is probably more efficient)
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
{:⁋,ẊṠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJ7OuKBiyzhuorhuaAiLCIiLCJcImFiXCIiXQ==)
```
{      # Forever
 :⁋,   # Print the current string joined by newlines
    ẊṠ # Take the cartesian product with the input
```
[Answer]
## Python, 55 bytes
```
s=input();l=['']
for x in l:print x;l+=[x+c for c in s]
```
This is longer than [feersum's 53-byte solution](https://codegolf.stackexchange.com/a/74277/20260), but it illustrates a different method with printed output. The list `l` is updated while it is iterated over, by appending every one-character suffix of each string that is read.
It's equally long to use `map`:
```
s=input();l=['']
for x in l:print x;l+=map(x.__add__,s) 
```
The same length can be done in Python 3, losing a char for `print()`, and saving one by input unpacking.
```
s,*l=input(),''
for x in l:print(x);l+=[x+c for c in s]
```
[Answer]
# [Zsh](https://www.zsh.org/), 31 bytes
```
f(){<<<${(F)a};a=($^a$^@);f $@}
```
[Try it online!](https://tio.run/##qyrO@P8/TUOz2sbGRqVaw00zsdY60VZDJS5RJc5B0zpNQcWh9n@aQqJC0n8A "Zsh – Try It Online")
Print the array, then zip on the arguments before recursing. Despite including the function name, this is one byte shorter than the iterative version:
```
for ((;;))<<<${(F)a}&&a=($^a$^@)
```
]