A representative but thoroughly useless and unscientific way to see how people write short pieces of code.
Write a function, method, or other similar construct in your favorite language that:
- accepts an array
arr
and a valuev
- returns the element in
arr
whose successor isv
, if there is such an element; otherwise return nothing
Test cases:
find_before([5, 6, 7], 6)
# => 5
find_before([5, 6, 7], 7)
# => 6
find_before([5, 6, 7], 5)
# => nothing
find_before([5, 6, 7], 999)
# => nothing
A literal translation of the requirements into C# would be:
This uses nullable types to allow
null
to be used as "nothing." Unfortunately, this restricts the types to integers, which is (generally) undesirable. We could use C# generics and restrict things to value types, but that's still less than ideal.A more ".NET-like" API would require changing the
find_before()
prototype, and making the method an extension method:Use:
The problem with this is that it requires using
out
parameters, though it is more consistent with the rest of the .NET framework.Finally, we could use Cadenza, a collection of types and utility methods, including a Maybe<T> type. This allows us to unify reference and value types, allowing something closer-in-spirit to the Ruby methods:
Use: