Skip to content

Instantly share code, notes, and snippets.

@jimwhite
Created July 2, 2024 22:54
Show Gist options
  • Save jimwhite/f598b1cece8ba7daf2254fb270389b59 to your computer and use it in GitHub Desktop.
Save jimwhite/f598b1cece8ba7daf2254fb270389b59 to your computer and use it in GitHub Desktop.
Fibonacci in Roc by ChatGPT
module [Fibonacci]
## Returns the Fibonacci sequence up to the nth term.
fibonacci : U32 -> List U32
fibonacci = \n ->
if n == 0 then
[]
else if n == 1 then
[0]
else
List.range 0 (n - 1)
|> List.foldl (\idx, acc ->
if idx == 0 then
List.concat acc [0]
else if idx == 1 then
List.concat acc [1]
else
let
last = List.get (List.len acc - 1) acc
secondLast = List.get (List.len acc - 2) acc
in
List.concat acc [(last + secondLast)]
) []
## Test cases
expect fibonacci 0 == []
expect fibonacci 1 == [0]
expect fibonacci 2 == [0, 1]
expect fibonacci 5 == [0, 1, 1, 2, 3]
expect fibonacci 10 == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment