Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Generic algorithms

Name: Anonymous 2008-11-28 11:31

Implement a single function that takes two arguments and returns the bigger of the two. Assume you don't know the type of the  arguments and you don't know if the types can be compared. Assume that if a type can be compared, it will always be implemented by following a single standard. Use the latest standard of your language. Write the simplest program
that will pass an integer 1(one) and a float 1.1(one point one) into the function and write the result to standard output.

Post the compiler you used, the code and the result.
Write what will happen if the max function is called with broken syntax (I'm looking at you C macros).
Write what will happen if the objects of a type can't be compared.

I'll start with C and C++.
Compiler: gcc 4.3.2 20081105 (Red Hat 4.3.2-7)
#include <iostream>
template<class F>
F& max(F& a, F& b) { return (a < b) ? b : a; }
int main() { std::cout << max(1, 1.1) << '\n'; }

Results: Compile time error:
max.cpp: In function ‘int main()’:
max.cpp:6: error: no matching function for call to ‘max(int, double)’

Bad syntax: Standard compile-time error
No comparison: Standard compile-time error about undefined operator<

#define max(a, b) (less(a, b) ? b : a)
#include <stdio.h>
int less(int a, int b) { return a < b; }
int main() { printf("%f\n", max(1, 1.1)); }

Result: Bad output
1.000000
Bad syntax: Depends on the error in the syntax. Can either compile and cause undefined behaviour or fail at compile time with strange syntax errors.
No comparison: Standard compile-time error about an undefined function.

Name: Anonymous 2008-11-28 14:01

This is biased towards weakly-typed languages, since 1 > 1.1 may not even be possible in strongly-typed languages.

Haskell
I'll assume the caller calls fromInteger. There's already a built-in max function, but for the purposes of demonstration,

max x y | x >= y = x
        | otherwise = y

main = print $ max (fromInteger 1) 1.1


Result: 1.1
Bad syntax: Fails to compile.
No comparison: Compile-time error about the missing Ord type class instance.

C++0x (theoretical, I haven't tried it)

#include <iostream>

template<typename T1, typename T2>
where LessThanComparable<T1, T2>
auto max(const T1& a, const T1& b) -> decltype(a + b) //This works by promoting the smaller type.
{
    if(a < b)
        return b;
    return a;
}

int main() {
    endl(std::cout << max(1, 1.1));
}


Result: 1.1
Bad syntax: compile-time error.
No comparison: compile-time error (comprehensible).

Ruby
def max a, b; a < b ? b : a; end

puts (max 1, 1.1)

Result: 1.1
Bad syntax: syntax error.
No comparison: runtime error.

INSTANT.EXE
Just press a few buttons and it's done.
Result: 1.1
Bad syntax: not possible.
No comparison: everything is comparable.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List