Recursion

In your favorite programming language, write a recursive function that returns the minimum number from a list of integers without modifying the list.

Perl 6:

sub find-minimum(@a) {
return @a.first if @a.elems == 1;
@a.first < find-minimum(@a.tail: *-1)
?? @a.first
!! find-minimum(@a.tail: *-1);
}

# abstracting the comparison away
sub infix:($a, $b) { $a < $b ?? $a !! $b }
sub find-minimum(@a) {
return @a.first if @a.elems == 1;
return @a.first find-minimum(@a.tail: *-1);
}

Attached: chin-recursion.jpg (640x640, 40K)

perl 6 looking pretty ugly there :( not sure if my code is much better though

elixir
def min([]), do: raise("can't min empty list")
def min([x | xs]), do: _min(x, xs)
defp _min(m, []), do: m
defp _min(m, [x | xs]) when x < m, do: _min(x, xs)
defp _min(m, [_x | xs]), do: _min(m, xs)

No need to recurse:
min(a)


But if you insist:
def find_minimum(a):
if len(a) == 1:
return a[0]

return min(a[0], find_minimum(a[1:]))

Using a built in language/library function is cheating in this exercise. It defeats the point.

Write it in assembler then, nerd

Could have been a simple Math.min or a for loop but here

Attached: Code_2019-04-08_17-20-56.jpg (848x844, 75K)

there's no recursion in assembly
recursion is a higher level construct

shhhhhhhhhh

>there's no recursion in assembly
what is call

function getmin(x, first=1, last=length(x))
if first>last
nothing
elseif first==last
x[first]
else
min(x[first], getmin(x, first+1, last))
end
end


Superior due to not copying the array so at least it's not an O(n^2) algorithm. Not superior due to not being tail call and no tail call optimization in Julia anyway.