# How do you create a loop in Chialisp?

This question was asked at chia_network.public on Keybase.

You have to declare a function that does something with the first item in a list, recursively calls itself with the rest of the list, then creates a cons pair of those results. It should return nil if there are no more items in the list, to terminate the cons pair. That will map to a new array. You can use a similar recursive structure for a standard for loop as well, but it’s less useful without side effects.

Here is a neat little example of the chiabot’s solution defining a length function in chialisp:
(mod (lst)
(defun length (lst)
(if (l lst)
(+ 1 (length (r lst)))
lst)
)
(length lst)
)

Compiles to:
brun ‘(a (q 2 2 (c 2 (c 5 ()))) (c (q 2 (i (l 5) (q 16 (q . 1) (a 2 (c 2 (c 13 ())))) (q . 5)) 1) 1))’ ‘((10 20))’

Which outputs:
2

brun ‘(a (q 2 2 (c 2 (c 5 ()))) (c (q 2 (i (l 5) (q 16 (q . 1) (a 2 (c 2 (c 13 ())))) (q . 5)) 1) 1))’ ‘((10 20 30))’

Outputs:
3

NOTE: If copying/pasting the above brun commands to the command line (my intention) then the apostrophes need to be changed to normal, non-directional apostrophes for the code to run successfully. This forum editor changed them and I can’t understand how to correct.

1 Like