[Question]
  [
# Task
Haskell's and Scala's standard libraries have an `unfold` function that builds a list from an initial state `s` and a function `f`. This is done with the following steps (explained in an imperative way to be simpler):
1. Apply `f` to `s`.
2. If the result
	* is empty, we're done building the list!
	* Otherwise, the result should contain the next state `t` and the next element `e` of the list.
		1. Add `e` to the list
		2. Set `s` to `t` and go back to step 1
Here, we will only be considering lists made of integers. `s` will be an integer, `f` will take an integer as input, and the result of your `unfold` function will be a list of integers. The output of `f` will either be
* A fixed value representing that the list has ended
* A class of values (distinct from the fixed value above) that hold an integer representing the next state and an integer representing the next element.
## Example
Let's take the example of converting a number to base 5. The initial state would be the number to convert. The output would be a list of the digits in base 5, but reversed. The function would look something like this:
```
function f(s)
   if s equals 0
      return null
   else
      digit = s mod 5
      nextState = s ÷ 5 (÷ is integer division here)
      return [nextState, digit]
```
Using this function and an example initial state of 137, we go through the following steps:
* `s = 137` and the result is `[]`
* `digit = 2`, `nextState = 27`. The result is now the list `[2]` and `s` is `27`.
* `digit = 2`, `nextState = 5`. The result is now the list `[2, 2]` and `s` is `5`.
* `digit = 0`, `nextState = 1`. The result is now the list `[2, 2, 0]` and `s` is `1`.
* `digit = 1`, `nextState = 0`. The result is now the list `[2, 2, 0, 1]` and `s` is `0`.
* Since `s` is 0, we return the list `[2, 2, 0, 1]`
Reversed, that's `[1, 0, 2, 2]` or `1022`, which, in base 5, equals 137. Note that this algorithm does not work with 0 or negative integers.
[Here](https://scastie.scala-lang.org/IcF0yY6qSYCuFh5nER4x4g) is an implementation in Scala.
As a test case, your `unfold` function should be able to convert positive integers from a base 10 to another base (as a reversed list of digits).
  
[Answer]
# [Factor](https://factorcode.org/), ~~37~~ 36 bytes
```
[ collector [ follow ] dip 1 head* ]
```
[Try it online!](https://tio.run/##FYwxCgIxEEV7T/FrQWUREfQAYmMjVssWIZmwwdlMnI2IXj7O8or/isePzlfR9rhfb5cTnqSZGJOrI2Z6vSl7mlGUav0WTbnivOr2R/RGNAbbA3aTBNMUNz9SwdB6eGGm5XkJzeVjQUgFHUZyYW2Rd8zYwjM5bX8 "Factor – Try It Online")
*-1 byte thanks to @chunes*
Takes `initial-value` and `quotation` on the stack, and returns a vector. The input quotation should return `next-state next-value` on the stack, or `f f` to terminate.
`some-quot collector [ high-order-func ] dip` is a pattern to snatch the top of the stack of every call of `some-quot` into a vector. Unfortunately, it collects the top of the stack before `follow` can detect that the loop has ended, so the resulting vector has a dummy element at the end. `1 head*` removes it.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~32~~ 29 bytes
Full program, prompting for `s` and then for `f`.
```
¯1↓r⊣⎕{1↓r,∘⊃←⍺⍺⍵}⍣{⍬≡⍺}⎕⊣r←⍬
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@f9qhtQjWXAhAY2D7q3Wr1qHcNmJeSmZ5ZApQzrQGKgkXyUitKgksSS1KBoo96uoDCh7ebItTqwOW5arkedbSX5qXl56T8P7Te8FHb5KJHXYsf9U2tBrN1HnXMeNTVDDKmdxcYba191Lu4Gmj1o86FQIFaoFKghiKwijX/gYb9VwADiJlchsbmXGkA "APL (Dyalog Unicode) – Try It Online")
`r←⍬` initialise the **r**esult variable to the empty list
`⎕⊣` dismiss that in favour of `s` from stdin
`⎕{`…`}⍣{⍬≡⍺}` get `f` from std and use it as follows until the result is the empty list:
 `⍺⍺⍵` apply `f` to the current `s` (returning `[e,t]` or `[]`)
 `r,∘⊃←` extend `r` with the first value from that (`e` or `0`)
 `1↓` drop the first value from that (leaving `[t]` or `[]`)
`r⊣` discard that (i.e. the last computed value, i.e. `[]`) in favour of `r`
`¯1↓` drop the last value (`0`)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 22 bytes
```
{-1_1_*'|'{x}(y@*:)\x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6rWNYw3jNdSr1GvrqjVqHTQstKMqajl4kqLNjQ2t65Wia6wNbA2sNaIr1A11dQxVayIrY0FAK++D28=)
call with `f[n,s]`.
`s` should return an array `(nextState;digit)` and return a falsy value when it's supposed to end.
I can remove `{x}` but that would make the function stop on a repeated state. Although that is unlikely, it doesn't seem right to reject that.
# Explanation
```
{-1_1_*'|'{x}(y@*:)\x}
                   \x
                       iterate on first arg, producing array
             (y@*:)    apply second arg(function) to the first elem of the iteration
          {x}          stop if the iteration is falsy
        |'             reverse each array
      *'               take first element of each
 -1_1_                 remove first and last element
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes
```
f=#@#2/.{a_,b_}:>b<>#~f~a&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2YLRMoOykb6etWJ8TpJ8bVWdkk2dsp1aXWJav8DijLzSqKVde3SHByUY9XqgpMT8@qquao906KVbW0NdKprdQJL80syU/NKgoAmZualpBZFK@uYxsaq6SgYGpvXctX@BwA "Wolfram Language (Mathematica) – Try It Online")
Input `[f, s]`. Returns a `StringJoin` of elements. Expects an empty list to indicate the list has ended.
To output a list, **+6 bytes**:
```
f=#@#2/.{a_,b_}:>{b,##&@@#~f~a}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2YLRMoOykb6etWJ8TpJ8bVWdtVJOsrKag4OynVpdYm1av8DijLzSqKVde3SgGKxanXByYl5ddVc1Z5p0cq2tgY61bU6gaX5JZmpeSVBQHMz81JSi6KVdUxjY9V0FAyNzWu5av8DAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 27 bytes
```
1 :'[:(#~2|i.@#)(,u@{:)^:_'
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRWs1KOtNJTrjGoy9RyUNTV0Sh2qrTTjrOLV/2typSZn5CtomKrVaOgo1xnYaGva6DmoqplqKqQpGBqb/wcA "J – Try It Online")
This is J adverb, which modifies a verb returning `(new element, new state)` to create the required unfold verb.
* `(,u@{:)^:_` Keep appending unfold's results until a fixed point, re-applying the verb to the last element on every iteration.
* `[:(#~2|i.@#)` Keep only odd indexed elements, ie, the elements only, and discard the states and the starting value.
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 46 bytes
```
(d U(q((S F)(i(F S)(c(h(t(F S)))(U(h(F S))F))(
```
[Try it online!](https://tio.run/##LYwxCsMwEAR7v2LLvSKEEEx@oNKN0QPkyCYHsp1Yavx6@RDpZgZ2i25n0vytlRGeP3KEEyodRuGbH5aGIvQmDZ1JZdpDRNLpCMcpHeO8YAp5vvVgCusUAzgIqAsGK5oLeDfsra17bCTYNNl1R4/H8/XfS70A "tinylisp – Try It Online")
### Ungolfed
Implements the spec directly:
```
(load library)
(def unfold
  (lambda (val func)
    (if (func val)
      (cons
        (head (tail (func val)))
        (unfold (head (func val)) func))
      nil)))
```
This approach is pretty inelegant: it's not tail-recursive, and it calls the function three times at each step. If I were going to implement `unfold` for the standard library, it would look more like this (using a helper function `_unfold`):
```
(def _unfold
  (lambda (func return-val accum)
    (if return-val
      (_unfold func
        (func (head return-val))
        (cons (head (tail return-val)) accum))
      (reverse accum))))
(def unfold
  (lambda (func val)
    (_unfold func (func val) nil)))
```
[Answer]
# JavaScript, 37 bytes
```
f=>g=s=>(a=f(s))?[a[1],...g(a[0])]:[]
```
[Try it online!](https://tio.run/##JcvBCsIwDADQv5EEZrG6XQbJPqTkELa1KCURu/n79eC7v5d@ta2f5/u4mm97Py173ahn4kKNGJQyNMQlaYoyhBAKaLoJypykr27N6x6qF/hPMGJbkjGPg13iJLOdtSLE@2OcEPsP "JavaScript (Node.js) – Try It Online")
`((state: T) => [next_state: T, val: S]?) => (state: T) => S[]`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Ṫv@¥ƬFḊ
```
[Try it online!](https://tio.run/##AS4A0f9qZWxsef//4bmqdkDCpcasRuG4iv///zE1OTc4/yJk4oG1VSTigJzigJ3CuT8i "Jelly – Try It Online")
A dyadic link taking the start value as its left argument and the Jelly code for the relevant function to unfold as its right. It expects the return value of this link to be an empty list if we’re done, otherwise a list of `[next value for result, next value for function]`. Returns a list of integers.
[Answer]
# [Haskell](https://www.haskell.org/), 22 bytes
```
f#x=do(s,v)<-f x;v:f#s
```
[Try it online!](https://tio.run/##VY1BDoIwFET3PcUkuGgTIBpDTFA8gAleAFkUaKGxAqFA8PLWEhbG5Z95b37DzVNobanHEMegHMEVGeU@Cpaz9diSIrfSW5Kqo8af2SWQWM5zLD1jp5@X8nchsMl/LpmQYH0RgspOVwONWZaHjJCCGxG5csIOj2XFlZtGkmCPsREt7t3YqLaG0EbgNpnRgZWa065yWETIi6vW@f2g2rXa9g7Hk/2UUvPa2KDs@y8 "Haskell – Try It Online")
Function is expected to return a list `[(state, value)]` or an empty list. (Footer converts from the conventional/expected use of `Maybe`.)
```
f#x=                      Define a function (#) on arguments f and x, returning
    do     <-f x;         the concatenation for each element of f called on x
      (s,v)               providing the new state and value
                 v:       of the value prepended to
                   f#s    (f#) called on the new state.
```
Was this before I remembered `MonadFail` is a thing (never mind I'm not even using it anymore):
# [Haskell](https://www.haskell.org/), 26 bytes
```
f#x|s:v<-f x=v++f#s|1>0=[]
```
[Try it online!](https://tio.run/##XY3RCoJAEEXf9ysu2INSghERSPYBgf2A@bDVri2Ziau2gd/eNmtE1LzMXOaee89cX0RZWt8LEMfwOcINMp4Hbn@ElZ4ZdNyvQwmT9NOp9PQw30RJltvui6X8cRB0z8CDH551kEjgOgoGmvtZNAIFzKg@M2Db6Ra@nqEPsA4JMoRlTud/zltLEXelhTPkjB24Fku6O0ywN65XjXSCCGStsCNCVQVESczYM8FJ9entRLYlY1euKuLrRlXu9c6bL1b2eZQlL7QNj3X9Ag "Haskell – Try It Online")
Function is expected to return a list `[state, value]` or an empty list.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 36 bytes
```
for($k,$a=$args;$a){$a,$u=&$k $a;$u}
```
[Try it online!](https://tio.run/##TY7BCoMwEETP5iv2sJUISiml9BDyJaWHpUYraiKroYfgt6dbKLS34c0wM0t4OV6fbpqaR2CXMfouTK1NuQuscayRLBL3q0GqElKN0ZY4ApLBuOddKextUgALMc36NvjtLkkBQ6dFQFIFsptp8K1jsCAQDnCpVMFui@xBf0gDv1AFR/HrP2KkbleyVX7vAfZwOl/zGw "PowerShell Core – Try It Online")
Takes two parameters, a function `$k` and the initial value `$a`
-1 byte thanks to *mazzy*!
[Answer]
# [Perl 5](https://www.perl.org/), 45 bytes
```
sub u{@f=$_[1]->(@_);@f?(pop@f,u(@f,pop)):()}
```
[Try it online!](https://tio.run/##HY1RCoJAFEX/W8VFLN/YZJQNRWK6jwwhcMiocRibIMLfFtAS24iN8uDcA/fC05W5ib5v7Rn2ncvUL4@r0@JAecmSXGakG51LbsnBKWN7Yt24lgJv3F/wlb2n7aWWj2R0ZKBaPWjwpWB8yKlg2IMYuok2roTnl/h9vvAQ4drUioKAw1TPyrQVLMEvOYqZe8HcRfAK5UE2Bqt4yx12Dut4IzjiUIThDnOIpP8D "Perl 5 – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 42 bytes
```
u=lambda f,x:(r:=f(x))and[r[1],*u(f,r[0])]
```
[Try it online!](https://tio.run/##TY3BCgIhFEXX@hWPWWm4mGGIYsAvMReGSoKj8tKwr7eJNu0u58C55V0fOa3XgqMln6MFCbfRZDT73Rrwom8MN@lZ59wkq1AtWpwa8wLVrLke1nn42o2S4KGDlDAfm6CrDRNMEyUuPt0fsuG1Z8u6gDOntGBIlf2@jyos64Xz8QE "Python 3.8 (pre-release) – Try It Online")
-1 byte thanks to Noodle9  
-4 bytes thanks to Shaggy
Assumes falsy output for the end case and a pair otherwise (any subscriptable value with at least two elements). Since a list of falsy values is still truthy, this works perfectly fine.
[Answer]
# [Racket](https://racket-lang.org/), `#lang racket`, 57 bytes
```
(define(u s f)(match(f s)[`(,z,x)(cons x(u z f))][_'()]))
```
[Try it online!](https://tio.run/##TYxBCsIwFET3nmKgC@dDF4qIGz1JKRrbRINpQpsUSi9foyL07d7wmEE1L52Wwin/wPATttpYrzkiwgg7lZonDaJUN5ZzOQmb4COmHMw5kLq6bim1yJKX/eEEOtXdWwVG2eAPrQHPl/y5W61AYdZGZ2MC@zEkq33K9VHALrSjC1/5sLwB "Racket – Try It Online")
The function `f` can return anything other than a list of two values to indicate stop.
---
Not the most interesting racket solution: no tail-call recursion, so is bounded by memory usage. It would be more fun (and not difficult) to write a `#lang` that supplies `unfold` as part of its runtime—then there would be a 0-byte solution :)
We (unexpectedly?) save a few bytes by eliminating spaces between `,z,x` and `_'()` in `match` clauses. I expected each to coalesce into a single identifier, but (un)quoting took precedence. The remaining whitespace (6 spaces, by my count) is required.
[Answer]
# [R](https://www.r-project.org/), ~~43~~ 42 bytes
```
u=function(s,l=f(s))if(1/l)c(l[2],u(l[1]))
```
[Try it online!](https://tio.run/##TY1BCoAgEADvvWIvwi4IYhGdfEBvCE/mgrAoZL7fjC6dZg4Dc/WWucjpenPccrhTyVi1OMZKlBitEQoox@x1G7CeqPMvJUhvCgErKKNg1TBkkCBKjbBnnr4F2mWj/gA "R – Try It Online")
Recursive function using helper function `f` to to the unfolding.
`f` must output the fixed non-integer value `Inf` to represent that the list has ended (a more natural value in [R](https://www.r-project.org/) would be `NULL` or `NA`, but the functions `is.null()` and `is.na()` are each much less golfy than the simple test `1/x` [truthy for all integers, falsy only for `Inf`])
]