Jenny
Jenny

Reputation: 5

How do these 'reverse' and 'twist' functions work in Ruby? (functional programming)

I redefined function fold using reduce method in Ruby.

def fold(f, init, lst)
    lst.reduce(init){|w, a| f.call(w, a)}
end

I have reverse and twist functions below and examples on how they should work.

reverse ‘(a b (c d) e)) --> (e (c d) b a)

def reverse(lst)
    fold(lambda{|w, a| [a] + w}, [] of Any, lst)
end

How is it possible to reverse an array with only [a] + w?? and what does [] of Any mean?

twist ‘(a b (c d) e)) --> (e (d c) b a)

def twist(lst)
    fold(lambda{|w, a| ([a.kind_of?(Array) ? twist(a) : a]) + w}, [], lst)
end

For twist function, I know it means that "if an element a is in the Array, it returns twist(a), and it it's not in the Array, it returns just a". But I don't get how this algorithm works..

Upvotes: 1

Views: 66

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369604

How is it possible to reverse an array with only [a] + w?? and what does [] of Any mean?

[] of Any is not legal Ruby syntax, it is a SyntaxError. Since the code is not even legal syntax, i.e. it cannot even be parsed, it makes no sense to analyze how it runs, because it can't run at all.

For twist function, I know it means that "if an element a is in the Array,

No, it means "if the element a is an Array (or more precisely, is a kind of Array)

it returns twist(a),

No, it returns [twist(a)] + w

and it it's not in the Array,

No, again, it means "if a is not an Array.

it returns just a".

No, it returns [a] + w.

But I don't get how this algorithm works..

a is the current element, w is the result that we have built up so far. If a is a simple element (not an Array), we return [a] + w, in other words, we move a to the beginning.

If a is an Array, we call twist on it first, then move it to the beginning.

Upvotes: 1

Related Questions