Last active
July 19, 2017 18:34
-
-
Save BadBastion/e5cf7c9699d19026c984441eb50e725c to your computer and use it in GitHub Desktop.
Increment LL cursor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def increment(enums, head) do | |
# enums, and all of their heads (start of list) | |
# accumulator = {carry, enums} | |
zip(enums, head) | |
|> foldr({true, []}, fn | |
{[_ | []], head}, {true, acc} -> {true, [head | acc]} | |
# {if the list has no more elements} and {carry in} -> {carry out and set back to begining on list (head)} | |
{[_ | tail], _head}, {true, acc} -> {false, [tail | acc]} | |
# {if the list does have more elements} and {carry in} -> {do NOT carry out and move to next element in list (tail)} | |
{enum, _head}, {false, acc} -> {false, [enum | acc]} | |
# {if there is no carry in} -> {do nothing} | |
end) | |
# the accumulator is {carry, enums}. For the sake of this example we will ignore the overflow carry and just return enums. | |
|> elem(1) | |
end | |
def to_cursor(enums) do | |
# returns the head of all lists in enums | |
enums |> map(fn [head | _] -> head end) | |
end | |
# example | |
two_bit_number = [[0,1], [0,1]] | |
two_bit_number |> increment() == [[0,1], [1]] | |
two_bit_number |> increment() |> to_cursor == [0,1] | |
two_bit_number | |
|> increment() | |
|> increment() | |
|> to_cursor == [1,0] # looks a lot like binary adding | |
# this increment function works on any base. For example: base 10 looks like [0..9, 0..9] | |
# this also works for mixed bases because it carry when a list is exhausted. For example: [0..9, 0..3] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment