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-12-04 23:10

>>111
"In a programming language of your choice, implement a function max(a,b), which returns the maximum of a and b. The types of a and b may not necessarily be the same, or even comparable. The type returned by the function must be the type of the maximum value passed in as a parameter, whatever it may be."

OK, this takes arguments of two types, a and b; a and b don't have to be comparable, but a must be convertible into b, and b must be able to compare. It will return either a value of type a if that argument was bigger, or of type b if that was bigger.

As >>94 said, you probably cannot exactly follow >>93's intent with a static type system. However, here, with Haskell's type classes, I've been able to achieve something very close.


class Convertible a b where
  convert :: a -> b

instance Convertible Int Float where
  convert = fromIntegral

myMax :: (Convertible a b, Ord b) => a -> b -> Either a b
myMax a b = let ba = convert a in
            if ba > b then Left a else Right b

main =
  do let x = 1 :: Int
     let y = 1.1 :: Float
     putStrLn $ show $ myMax x y

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