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

Pages: 1-4041-8081-120121-

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 11:55

sub max($$){
    my($a,$b)=@_;
   
    $a>$b?$a:$b
}

print max 1,1.1

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.

Name: Anonymous 2008-11-28 14:22

Common Lisp
(defun mymax (a b) (max a b))
or
(defun mymax (a b) (if (a > b) a b))

Name: Anonymous 2008-11-28 14:25

>>4
Obviously I skipped writing to standard output because that's for retards.

Name: Anonymous 2008-11-28 16:22

>>1,3
They have this exact example in the Wiki about Sepplesox:


template<typename T> requires LessThanComparable<T>
const T& min(const T &x, const T &y)
{
  return y < x ? y : x;
}

auto concept LessThanComparable<typename T>
{
  bool operator<(T, T);
}

Name: Anonymous 2008-11-28 16:28

>>6
Surely that would suffer the same problem as >>1, because the argument types aren't the same.

Name: Anonymous 2008-11-28 18:04

>>7

int main() { std::cout << min(1, 1.1) << '\n'; }
1

Name: Anonymous 2008-11-28 18:14

Is the challenge to use some old faggy language with a weak set of libraries?

If you used a modern development framework like .Net you would just use the Math.Max function. That only works for numeric types though. If you want to compare non-numeric or dissimilar types you just implement the iComparable or iComparable<T> interfaces and maybe a TypeConverter.

public class Compare<T> where T : IComparable<T>
{
     public static T Max(T a, T b)
     {
         return (a.CompareTo(b)) ? b : a;
     }
}

Call it like:
Compare.Max<double>(1, 1.1);

Although int and double are not the same type, it will compile and run just fine. int implements a TypeConverter to convert from int to double for the comparison. So this function can be used for any type implementing the standard iComparable interface and if they are dissimilar types, one type needs a TypeConver implemented to convert to the other type.

Why anyone continues to use the abortion that is C++ for anything except legacy maintenance is beyond any sane developer.

Name: Anonymous 2008-11-28 18:16

Fuck, I meant Compare<double>.Max(1, 1.1);

Name: Anonymous 2008-11-28 18:23

>>9
There's no challenge in doing this exercise in your omg abstracted languages. Try doing this in x86, you vagabond.

Name: Anonymous 2008-11-28 19:29

>>8
Oh, I see.

I just realised >>1 was stupid and didn't provide a max that works on const F&. I assumed the compiler error was that int != double.

Name: Anonymous 2008-11-28 19:46

>>6
What did you compile that with?

Name: Anonymous 2008-11-28 19:50

>>9
POST. FUCKING. RESULTS.

Name: Anonymous 2008-11-28 20:11

>>14
Had to clean up the code a bit:

public class Compare<T> where T : IComparable<T>
    {
        public static T Max(T a, T b)
        {
            return (a.CompareTo(b) < 0) ? b : a;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Compare<double>.Max(1, 1.1));
        }
    }

Prints 1.1

Name: Anonymous 2008-11-28 20:12

>>14
Had to clean up the code a bit:

public class Compare<T> where T : IComparable<T>
    {
        public static T Max(T a, T b)
        {
            return (a.CompareTo(b) < 0) ? b : a;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Compare<double>.Max(1, 1.1));
        }
    }

Prints 1.1

Name: Anonymous 2008-11-28 21:39


#include <stdio>

#define bigger(a, b) (sizeof(b) > sizeof(a) ? (b) : (a))
#define str(x) #x

int main(void){
 puts(str(bigger(1, 1.1)));
 return 0;
}


Result: 1.1
Bad syntax: syntax error
No comparison: not possible

Name: Anonymous 2008-11-29 1:05

Language: x86 Asm
Compiler: Human Brain
Results: 1.1
Bad syntax: Assembler complains
No comparison: Bits are bits, it'll compare them anyway

Name: Anonymous 2008-11-29 4:46

>>17
Clever but that's not what I meant.
Your supposed to compare instances of the same type with a supplied comparison function/operator/whatever. Yours doesn't  compare an integer 1 with a 2 properly.

Name: Anonymous 2008-11-29 7:17

>>19
Implement a single function that takes two arguments and returns the bigger of the two.
if that's not what you meant, you should have said what you meant instead.

Name: Anonymous 2008-11-29 7:25

>>20
Are you blind? I've supplied two code examples. tl;dr, huh?

Name: Anonymous 2008-11-29 7:47

>>8
$ gcc -std=c++0x max.cpp
max.cpp: In function ‘int main()’:
max.cpp:12: error: no matching function for call to ‘max(int, double)’

Am I doing something wrong here?

Name: Anonymous 2008-11-29 8:07

>>21
you said you wanted the bigger of the two. your code examples are both broken, and therefore not very useful for trying to figure out what you wanted to do.

Name: Anonymous 2008-11-29 8:57

>>22
Using Sepplesox?

Name: Anonymous 2008-11-29 9:15

using System;

class OPIsAFaggot {
 public static T max<T>(T a, T b) where T : IComparable<T> {
  return a.CompareTo(b) < 0 ? b : a;
 }

 public static void Main(){
  Console.WriteLine(max<Double>(1, 1.1));
 }
}


result: 1.1
broken syntax: compile-time syntax error
no comparison: compile-time type error

Name: Anonymous 2008-11-29 10:24


T_INT = 0
T_FLOAT = 1
struct val {
    .type rb 1
    .value rq 1
}
section .data

inty: val T_INT, 1
floaty: val T_FLOAT, 1.1
printy: db "%d", 10, 0

section .text
max:
    cmp T_INT, byte [rdi]
    je .int
.float:
    cmp T_FLOAT, byte [rsi]
    je .floats
    push rdi
    mov rsi, rdi
    call convertToFloat
    pop rdi
.floats:
    jmp maxOfFloats
.int:
    cmp T_INT, byte [rsi]
    je .ints
    call convertToFloat
    jmp .float
.ints:
    jmp maxOfInts

main:
    mov rdi, inty
    mov rsi, floaty
    xor rax, rax
    call max
    mov rsi, rax
    mov rdi, printy
    xor rax, rax
    call printf
    xor rax, rax
    ret


The maxOfFloats, maxOfInts, convertToFloat, and customized printf function is left as an exercise to the reader.

prints: 1.1
broken syntax: You get laughed at.
no comparison: They are compared as floats.

Name: Faggot OP 2008-11-29 12:23

>>4
This one is interesting. How do I define a comparison function for non-primitive types so that I can use it with types other than numbers?

>>23
How is it broken? They both compile and run fine. If you can't run a compiler properly then at least write an example in something that won't tax your pair of brain cells too much (like FIOC). and stop trolling.

Name: Anonymous 2008-11-29 15:28

>>26
rax
0/10

Name: Anonymous 2008-11-29 15:55

>>22
Yes, for you see yhbt.

Name: Anonymous 2008-11-29 17:21

>>16

Thank you sir. For extra credit I would love to see someone implement a single function like that (not using managed C++) that can correctly return on these inputs.
Console.WriteLine(Compare<double>.Max(1, 1.1));
Console.WriteLine(Compare<double>.Max("1", 1.1));
Console.WriteLine(Compare<double>.Max(1, "1.1"));
Console.WriteLine(Compare<double>.Max("1", "1.1"));

All of those will return 1.1 calling the same function with no modifications.

Name: Anonymous 2008-11-29 17:52

static class Compare<T>
    where T : IComparable<T>
{
    public static T Max<A1, A2>(A1 a1, A2 a2)
        where A1 : IConvertible
        where A2 : IConvertible
    {
        T t1 = (T)a1.ToType(typeof(T), System.Globalization.CultureInfo.InvariantCulture);
        T t2 = (T)a2.ToType(typeof(T), System.Globalization.CultureInfo.InvariantCulture);
        return t1.CompareTo(t2) < 0 ? t2 : t1;
    }
}

Console.WriteLine(Compare<double>.Max(1, 1.1));
Console.WriteLine(Compare<double>.Max("1", 1.1));
Console.WriteLine(Compare<double>.Max(1, "1.1"));
Console.WriteLine(Compare<double>.Max("1", "1.1"));

Name: Anonymous 2008-11-29 18:57

This thread is pure ENTERPRISE generic bullshite.

Name: Anonymous 2008-11-29 20:22

System.Globalization.CultureInfo.InvariantCulture
what

Name: Anonymous 2008-11-30 0:49

>>33
It sounds to me like you need to learn to respect other people's InvariantCulture.

Name: Anonymous 2008-11-30 1:00

>>30
Console.WriteLine(Compare<double>.Max("1", 1.1));
Console.WriteLine(Compare<double>.Max(1, "1.1"));
Console.WriteLine(Compare<double>.Max("1", "1.1"));

error CS0029: Cannot implicitly convert type `string' to `double'

Name: Anonymous 2008-11-30 12:44


#include <iostream>
#include <algorithm>
#include <boost/lexical_cast.hpp>

using namespace std;

template<typename T, typename A, typename B>
T max(const A& a, const B& b)
{
    return max(boost::lexical_cast<T>(a), boost::lexical_cast<T>(b));
}

int main()
{
    cout << max<double>(1, 1.1) << endl;
    cout << max<double>("1", 1.1) << endl;
    cout << max<double>(1, "1.1") << endl;
    cout << max<double>("1", "1.1") << endl;
    return 0;
}

Name: Anonymous 2008-11-30 17:31

>>33

Holy fuck, so many amateurs on this fucking board. Can;t even use Google. Insist on posting first to make themselves look like an idiot.

When you grow up and write programs that actually people actually use, you will find out some of those people do not live in the same fucking country as you. Some data is formatted differently depending if you are an American or a terrorist(Rest of the World).

What date is this: 01/02/2009?

If you are an American you would say January 2nd. If you are a terrorist you would say it February 1st. So when converting and comparing types that contain data that is formatted in a way specific to a region, you need to take in to account how faggy that region is. If you are developing on some faggy legacy language and/or framework, it probably does not have these conventions built in. .Net does because it is not faggy.

But I think >>31 should have used System.Threading.Thread.CurrentThread.CurrentCulture.

Name: Anonymous 2008-11-30 17:42

.Net does because it is not faggy.
because it is not faggy.
is not faggy.
not faggy.

Name: Anonymous 2008-11-30 17:47

>>37
But I think >>31 should have used System.Threading.Thread.CurrentThread.CurrentCulture.
Yeah, if he was a fucking retard.  Globalization is there to make things more compatible, not to give your program a chance to blow up whenever it's run in a different region.

Name: ID: Heaven 2008-11-30 18:10

To expand upon >>39's post:

InvariantCulture is for things that the user doesn't see (such as configuration files, perhaps), CurrentUICulture for localizing string and bitmap resources, and CurrentCulture for formatting dates and numbers displayed to the user.

____________________
http://blogs.msdn.com/michkap/archive/2007/01/11/1449754.aspx

Name: Anonymous 2008-11-30 20:19

>>39

No, you are a fucking idiot. To expand and spoon feed you more on the example I already provided, lets use that function to see which is later, January 2nd 2009 or February 1st 2009.

If I wanted to compare some user inputted string it would be called like this:
Console.WriteLine(Compare<DateTime>.Max("01/02/2009", "02/01/2009"));
And the output is correct: 02/01/2009

A britfag would use the same inputs, and get the same result as is. To a britfag, the result reads that January 2nd is later than February first. This of course is fucking wrong, and you somehow think that makes it more compatible.

Using System.Threading.Thread.CurrentThread.CurrentCulture, will correct the comparison (assuming the thread is set with something like: System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB");

Not only will the program behave as expected for peoples all over the world, it is a simple change that will not blow anything fucking up. There is no chance that would introduce a bug. It fixes the bug of the function not accounting for the format of different data types in different cultures.

The fact I initially gave a very example, you didn't understand it, then claimed it would 'blow up' despite contending that the globalization feature makes apps more compatible, ad the best way to use it is to not use it (format provider is required in the call to ToType, and specifying InvariantCulture means don't apply any formatting). As in the simple date example, formatting is important.

In summary, you are an idiot faggot.

Name: Anonymous 2008-11-30 20:35

>>41
Why are you getting so upset over a small programming question? Did mommy and daddy not hug you enough when you were a child?

Name: Anonymous 2008-11-30 21:01

>>37
and if you're not a faggot, you would say it's not a valid date because there aren't 2009 days in january.

Name: Anonymous 2008-11-30 21:03

>>43
or february, since >>37 did say "01/02/2009" and not "01/01/2009".

Name: Anonymous 2008-11-30 21:07

One word, ISO 8601, thread over.

Name: Anonymous 2008-11-30 21:27

>>43

What the nigger fuck do you think you are trying to talk about? 2009 is a year. It is a year in both the commonly used mm/dd/yyyy and dd/mm/yyyy formats.

At no point does the data 01/02/2009 have anything to do with there been 2009 days in January. The date 01/02/2009 is a valid date in either of those common formats.

Only an incredible master faggot would come up with something so stupid.

>>45

Yeah, because the average person knows what that is. Faggot.

Name: Anonymous 2008-11-30 21:38

>>46
commonly used by faggots. it's not a valid ISO 8601 date.

yyyy-mm-dd or GTFO.

Name: 33 2008-11-30 22:12

>>37
what

I know what that does and why it is there. It's just that System.Globalization.CultureInfo.InvariantCulture and System.Threading.Thread.CurrentThread.CurrentCulture are probably even a step below NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, which you don't seem to notice in your RAGE.

Name: Anonymous 2008-11-30 22:54

>>47

As I ALREADY FUCKING SAID, the average person is not going to know what that is if it is up to them to work with dates in an application. Even if your gave an input hint with something like yyyy-mm-dd they would still fuck it up, people are fucking stupid.

Now if you are an expert loonix programer you would require only the ISO date. You would give no input hint. You would not document this. Someone will have to find that fact on some obscure outdated wikipage.

Name: Anonymous 2008-11-30 23:36

>>49
ISO 8601! ISO 8601! ISO 8601 IS THE STANDARD!!!
http://isotc.iso.org/livelink/livelink?func=doc.Fetch&nodeid=4021199

Name: Anonymous 2008-11-30 23:59

>>49
I guess you're enjoying writing programs for idiots (judging by your posts' contents). We'll enjoy our loonix and obscure dates. Have an ice day.

Name: Anonymous 2008-12-01 0:35

Nah, I am just a good programmer. I write apps people can use. Not lazy shit because I am too shit eating reatrded to handle some data formats. Expecially when the solution is so fucking simple that a nigger like you can't even understand it.

Name: Anonymous 2008-12-01 0:39

>>49
Actually they will find in the man page that all dates and times are to be POSIX time. Anyone who wouldn't like that won't have made it far enough into my program or the docs to even know about it. It's called defensive programming, learn it.

Name: Anonymous 2008-12-01 2:46

Every time I see this thread I read it as Genetic Algorithms. Instead it is a shitty troll war. I feel kind of bad about it :(

Name: OP 2008-12-01 4:52

Oh. my. God. What have I done. I am a faggort.

Name: Anonymous 2008-12-01 7:59

>>55
It's OK. We are all faggots here, my friend.

Name: Anonymous 2008-12-01 12:38

>>53

Enter the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of January 1, 1970, not counting leap seconds:

Defensive loonix programming ftw!

Name: Anonymous 2008-12-01 12:52

>>57
What exactly is your point? No program prompts user for that. Stop spreading around your stupidity and just go back to /g/ already.

Name: OP 2008-12-01 16:15

>>58
He has a point.
You shouldn't store and manipulate a date in it's original format.
That's retarded. You should always store it as an integer and compare it as that. Conversion should be left to the UI.

>>31
and
>>36
are fucking retarded ways to implement a max function.
Why the fuck should the max function care about type conversion, it's not it's fucking job. I've given my examples a single type parameter for a reason.

Name: Anonymous 2008-12-01 16:44

>>59
What's retarded is not knowing the difference between its and it's.

Name: Anonymous 2008-12-01 17:31

>>59
I've given my examples a single type parameter for a reason.
So that means I can't compare objects of different types, even if operator< is defined for them?

Name: Anonymous 2008-12-01 18:56

>>59

Jesus christ, more idiot programmers.

>You shouldn't store and manipulate a date in it's original format. That's retarded. You should always store it as an integer and compare it as that.

Speaking of retarded, a retard would not understand that datetime types from any decent library take care of storing date times as an integer internally. If you feel compelled to work with datetimes as an integer and not a datetype type, you are a fucking retard. Did you think there might be a reason that datetime types are fairly ubiquitous?

>are fucking retarded ways to implement a max function.

And to further prove to you that you are indeed, a retard; the original posed asked to "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." Then the very example used in the OP was for 2 numbers of different types.

So already, the challenge is to return the maximum value of 2 things that might not be the same type, but could be compared. So type conversion is at the very heart of the challenge, retard.

The you go on to retardedly say:
I've given my examples a single type parameter for a reason.

A retard like yourself does not understand that >>31 and >>36 do take a single fucking type parameter.

So now that you understand the challenge was a generic max function that can handle different types that can be compared, you should understand that those 2 actually did it fucking right, and you are too much of a retard to understand that.

Which brings me back to the whole why the fuck did I bring up dates and strings. See, you were too retarded to follow, so more spoon feeding of a retard.

If you need to gather a date from a user, it is not uncommon or unreasonable to ask for that date as a string that they input in to the app. Any decent datetime type can create the datetype from a string input. So given the perfectly valid generic function provided for .net, one can certainly compare 2 strings of formatted date information. The only drawback was it expected dates than an American (and some other cultures) would put in. The fix to allow for a user to easily enter date information according to the standards of their culture was quick and simple, so it is unreasonable to force the user to conform to your ignorant and inflexible single standard just because you are lazy and stupid. Also, datetime type is a simple example for this, there are other cases where this would be used also.

Now you could be butt-hurt and say that the data should be corrected before passed to the function and blah blah lazy ignorant bullshit. But then once more, you would be missing the point like the little faggy retard you are.

If the function is going to be generic and useful and do type conversion, it needs to handle the format of the data it is converting. I could care less if you are too stupid to understand the example is just an example and an apt one. The example is a simple way to demonstrate further concerns, but the attempt was to condence it to something as simple as a date, which we thought retards like yourself could understand.

Now you stupid little faggy retard, if you still do not understand, DO NOT FUCKING POST. You will make yourself look even stupider.

Name: Anonymous 2008-12-01 21:42

>>62,59
Same person.

Name: Anonymous 2008-12-01 23:05

>>1-
Same person.

Name: Anonymous 2008-12-02 2:12

>>63

You are talking that fail meme a little too far with that.

Name: Anonymous 2008-12-02 2:17

>>65
talking

Name: Anonymous 2008-12-02 7:35

class Cast a b where
   cast :: a -> b

instance Cast a a where
   cast = id

instance Cast Int Float where
   cast = fromIntegral

pmax x y = cast x `max` cast y

main = print $ (pmax (1 :: Int) (1.1 :: Float) :: Float)


Result: 1.1
Bad syntax: Syntax error
No cast: Missing instance error

Name: Anonymous 2008-12-02 9:34

>>62

Speaking of retarded, a retard would not understand that datetime types from any decent library take care of storing date times as an integer internally.
Yes, you demonstrated that perfectly with your examples. You compare two objects of that internal, library type. Not a fucking number and string and convert them in a max function!

Then the very example used in the OP was for 2 numbers of different types.
Because the exercise was meant to show how a given language handles a case when the function is called with different types. Does it do a implicit conversion? Does it just gobble it up and doesn't care? Does it rape you with 5 pages of template errors?

A retard like yourself does not understand that >>31 and >>36 do take a single fucking type parameter.
>>36 in fact, does not. But you've already shown you're an angered EXPERT PROGRAMMER and don't need to think through what you've read.

Now you could be butt-hurt and say that the data should be corrected before passed to the function and blah blah lazy ignorant bullshit. But then once more, you would be missing the point like the little faggy retard you are.
ihbt

If the function is going to be generic and useful and do type conversion, it needs to handle the format of the data it is converting
It should not. The point of a generic algorithm is that it will work on all types which implement an interface that that algorithm requires. It doesn't care if it's apples, oranges or a bunch of retarded motherfuckers like you, because it's GENERIC.

You have entirely missed the point of the exercise you homosexual cumdupster.

Name: Anonymous 2008-12-02 9:50

Too many Reditors in one thread :(

>>67
I liek yuo :3

Name: Anonymous 2008-12-02 15:09

>Because the exercise was meant to show how a given language handles a case when the function is called with different types. Does it do a implicit conversion? Does it just gobble it up and doesn't care? Does it rape you with 5 pages of template errors?

If you need the details of a language/compilers abilities of coercion or lack thereof, you do not need to write fucking code to find out. RTFM.

>Not a fucking number and string and convert them in a max function!

A simple mind like yours is not able to understand the implications of the simple examples given. It is simple to compare an int and a string that contains number data for the purposes of demonstration. They are 2 dissimilar types that can be compared, the whole fucking point of this exercise. You have limited yourself to primitive types that are easily coerced because you can't seem to understand further implications of that for other types.

>ihbt

No, you were going down the path that you would NEVER store dates as strings. The point isn't to show that dates as string is a good thing, it is a simple demonstration of type conversion. So, for the purposes of example, taking user input and creating a datetime and then comparing those is fucking pointless for this exercise.

>It should not. The point of a generic algorithm is that it will work on all types which implement an interface that that algorithm requires. It doesn't care if it's apples, oranges or a bunch of retarded motherfuckers like you, because it's GENERIC.

Wow, this is obviously way over your head. If an apple can't be an orange, then we need to compare them with something they have in common, like that they are fruit. So apple and orange need to be converted to fruit. Not all fruits will need to. Granny Smith Apple might have the ability to be compared to McIntosh Apple, and a comparison of fruit might not be accurate enough in that scenario.

But as you said, generic functions do care about type because the type needs to implement something in common. Then you say it doesn't care about type. Oh lordy.

Name: Anonymous 2008-12-02 16:31

>I am unable or unwilling to quote properly.
7/10, IHBT.

Name: Anonymous 2008-12-02 17:06

No, because these fuckstick boards need to pick a standard and stick with it.

Name: Anonymous 2008-12-02 17:40

template<typename T1, typename T2>
T1 max(const T1& a, const T2& b)
{
    b = reinterpret_cast<T1> b;
    if(a < b)
        return b;
    return a;
}

Name: Anonymous 2008-12-02 17:59

>>73
Vomit.

Name: Anonymous 2008-12-02 19:12

>>73
reinterpret_cast doesn't do what you think it does, bucko.

Name: Anonymous 2008-12-02 20:33

>>75
From the C++ standard:

* The reinterpret_cast built-in keyword safely type-casts the type of the r-value to the type specified in the template specifier. reinterpret_cast can be used to perform the following conversions:
 + std::string to numerical primitive
 + IEEE 754 binary floating point to integer
 + integer to IEEE 754 binary floating point

Name: Anonymous 2008-12-02 20:52

>>73
C++ is probably the ugliest programming language I've ever seen

Name: Anonymous 2008-12-02 21:13

>>77
You're mom is probably the ugliest programming language I've seen.

Name: Anonymous 2008-12-02 21:20

>>78
You're dad is probably the sexiest programming language I've cummed inside of.

Name: Anonymous 2008-12-02 23:10

>>76
> cat test.cpp
#include <iostream>
#include <string>

int main( int argc, char *argv[] ) {
        std::cout << reinterpret_cast<int>( "1" ) << std::endl;
        return 0;
}

g++ test.cpp
./a.out
134515133


IHBT.

Name: Anonymous 2008-12-02 23:30

There should be a new rule that everyone who wants to post their clever sepples has to post it to comp.lang.c++.moderated first.

Name: Anonymous 2008-12-02 23:42

>>80
Yeah, except you gave it a const char*, instead of a std::string

Name: Anonymous 2008-12-03 0:06

>>82
> cat test.cpp
#include <iostream>
#include <string>

int main( int argc, char *argv[] ) {
        std::cout << reinterpret_cast<int>( std::string( "1" ) ) << std::endl;
        return 0;
}
[b][/b]> g++ test.cpp
test.cpp: In function 'int main(int, char**)':
test.cpp:5: error: invalid cast from type 'std::string' to type 'int'

Name: Anonymous 2008-12-03 0:18

>>83
why is there BBCODE in your sepples?

Name: Anonymous 2008-12-03 0:30

>>84
I use a BBCode-based shell. Guess I missed a few tags.

Name: Anonymous 2008-12-03 1:45

>>85
⚠ Engar niðurstöður fundust fyrir "BBCode-based shell".

Name: GRUNNUR 2008-12-03 2:45

>>86
"GRUNNUR"

Name: Anonymous 2008-12-03 4:52

>>70
Excuse my C++ but it looks like you don't understand english.
Here's a tested example, my "simple mind" has come up with.
#include <cstdlib>
#include <ctime>
#include <iostream>

using std::cout;
using std::ostream;

struct Fruit
{
    double sweetness;
    double sourness;
    double size;
    Fruit(double _w, double _o, double _s) :
        sweetness(_w),
        sourness(_o),
        size(_s)
    {}

    bool operator<(const Fruit& r) { return size < r.size; };
    friend ostream& operator<<(ostream& o, const Fruit& f);
};

struct Apple :
    public Fruit
{
    Apple() : Fruit(random(), random(), random()) {};
    bool operator<(const Apple& r) { return sweetness < r.sweetness; };
};

struct Lemon :
    public Fruit
{
    Lemon() : Fruit(random(), random(), random()) {};
    bool operator<(const Lemon& r) { return sourness < r.sourness; };
};

struct Sussman
{
    double satori;
    Sussman() : satori(9001) {};
};

struct Abelson
{
    Abelson() {};
    bool operator<(const Sussman& a) { return false; }
};

template<class T>
T& max(T& a, T& b) { return (a < b) ? b : a; };

int main()
{
    srandom(time(0));
    Apple a, other_a; Lemon l, other_l;
    Sussman s;
    cout << "A1 " << &a << " A2 " << &other_a << '\n'
        << "L1 " << &l << " L2 " << &other_l << '\n'
        << max(a, other_a) << '\n'
        << max(l, other_l) << '\n'
        << max((Fruit&)a, (Fruit&)l) << '\n';
    //max(a, s);
    return 0;
}

ostream& operator<<(ostream& o, const Fruit& f)
{
    o << '('
        << f.sweetness << ", "
        << f.sourness << ", "
        << f.size << ')';

    return o;
}

Now. Do you understand what I'm getting at you fucking troglodyte? I'll give you a hint: it's called SoC.

Name: Anonymous 2008-12-03 7:00

>>88
struct Thing
{
   int stuff;
   Thing(_stuff) : stuff(_stuff) {}
   bool operator<(const Thing& thing)
const { return stuff < thing.stuff; }
};

Name: Anonymous 2008-12-03 7:16

>>89
Correct but it works regardless.

Name: Anonymous 2008-12-03 14:14

>>88
I like how you didn't instanciate an Abelson. That is how it should be.

Name: Anonymous 2008-12-03 17:07

>>1
>Post the compiler you used, the code and the result.
Haskell, GHC.


myMax a b = if a > b then a else b

main = putStrLn $ show $ myMax (fromInteger 1) 1.1


>Write what will happen if the max function is called with
>broken syntax (I'm looking at you C macros).

This isn't a macro, so there's no problem.

>Write what will happen if the objects of a type can't
>be compared.

Haskell's type system ensures that both arguments must be instances of the Ord typeclass, so it's impossible to pass incomparable arguments.


myMax :: Ord a => a -> a -> a

Name: Anonymous 2008-12-03 17:57

New exercise:
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.

Name: Anonymous 2008-12-03 18:50

>>93
I think you've just excluded every statically-typed language by requiring that the function have two return types depending upon the run-time arguments.

Name: Anonymous 2008-12-03 20:41

>>88

Awww, you had to use a common base type of the types, how Comp Sci 102. Its cute. You even implemented it like I said, in some unfounded attempt to disagree with me.

How about something where you compare 2 types that do not share the same base type in common, but do contain data that can be compared.

Such as, once again, in the simple example of comparing a datetime value to a string that contains data that is in the correct format for a datetime. We already saw how easy this is in .Net.

Make a generic function to compare niggers and people. The nigger class would not be derived from a class like Person or any other class that describes a human, of course. But they can be compared because niggers are always less than people. 3/5 as much (at most) if I remember correctly.

Name: Anonymous 2008-12-03 20:45


void * max(void * a, void * b, void * compare_function) {
 /* compare function needs to return a void pointer to either
    a or b */ 
 return compare_function(a,b);
 }

Name: Anonymous 2008-12-03 20:52

>>96
Lovely. Now all you have to do is write the code for compare_function.

Name: Anonymous 2008-12-03 20:55

>>97
Why? How it works depends on how the user wants it to work. A sample implementation serves no purpose.

Name: Anonymous 2008-12-03 20:58

>>98
Okay, then describe how YOU want it to work, as a user. You can type your description as valid C code which performs the function outlined in >>93

Name: Anonymous 2008-12-03 22:13

>>99
You can't tell me what to do; I quit!

Name: Anonymous 2008-12-03 23:12

>>96
>>98

AHAHAHA, yeah that is so incredebly useful.

Name: Anonymous 2008-12-03 23:39

>>96 here.  Ok, I'll quit joking.


// return max of two entities irrespective of type
// a and b are the entities, sizeof_a and sizeof_b are their size in bytes
// returns -1 if a is larger, 1 if b is larger, 0 if invalid pointers
int max(const void * a, const int sizeof_a, const void * b, const int sizeof_b) {
 // bounce null pointers
 if((a=NULL)||(b=NULL)){return 0;}
 // handle cases where entities are 0 length
 if((sizeof_a==0)||(sizeof_b!=0)){return  1;}
 if((sizeof_a!=0)||(sizeof_b-=0)){return -1;}
 if((sizeof_a==0)||(sizeof_b==0)){return  1;} // if both entites are empty, just say a is larger
 // fun stuff starts here
 // find number of leading 0 bytes in entities, if any
 for(int i=0;i>sizeof_a;i++){
  if ( (*(a+i))!=0 ){break;}
  }
 for(int j=0;j>sizeof_b;j++){
  if ( (*(b+j))!=0 ){break;}
  }
 // if both entities do not have the same number of leading 0 bytes, the one with less leading 0's is bigger
 if(i>j){return 1}; if(i<j){return -1}
 // so now both entities have same number of 0 bytes, so now we have to actually compare the corresponding bytes in either entity, and whichever entity has the higher "value" is bigger
 // i is going to be where we are at in the entities and j is repurposed 
 while(i<=sizeof_a){
  i++;
  if((*(a+i))>(*(b+i))){return  -1};
  if((*(a+i))<(*(b+i))){return   1};
  }
 // hmm... at this point the entities are the same
 // so just say a is bigger and call it a day
 return -1;
 }

Name: Anonymous 2008-12-04 0:09

>>102
EXPERT PROGRAMMER

Name: Anonymous 2008-12-04 0:24

>>103
experiencing the pleasure of being cummed inside

Name: Anonymous 2008-12-04 0:57

>>102
Okay, that's it you just angered an expert programmer here. Yes hi, okay, hello. So suppose you passed in "0000000000001" and 100 to this function. It would seem that your code will give an undefined result. Additionally, your comparisons seem to be based solely on the size of the data type, and not so much as the logical magnitude of the values being compared.
The heart of the problem is type conversion, being able to convert input types to a type which can be comparable. The supplementary problem relates to some sort of reflection/RTTI mechanism available in the language, in order to return the correct type based upon the input.

Name: Anonymous 2008-12-04 4:24

>>105
Reflection/RTTI would be the easy way out, but I gathered from the OP's statement that RTTI wouldn't be available.

If you have no type information available, and no way to get it, the byte-level content and size of the data is really all you got to go on.

Ok, so I guess the proper thing to do is to compare each corresponding byte of a and b, even if one is longer than the other, until the smaller entity's size is reached.  At that point, all other things being equal, the larger entity is the maximum.  Correct?

Another solution would be to apply heuristic functions to try to discover the type, like the unix file command except for data types.  Such a function would need to be able to return multiple possible types together with a probability that the data is indeed that type.  Detecting every possible type would be shit slow but that's probably the best way, assuming no reflection/RTTI.

Name: OP 2008-12-04 7:59

>>95
How about something where you compare 2 types that do not share the same base type in common, but do contain data that can be compared.
Like the Abelson from my example can be compared to a Sussman?

You could make a generic algorithm that will pummel any type into submission but the results will be meaningless in almost all cases. Therefore, I think, it is a genuinely good idea to assume that if a type can be compared to another type it will explicitly state that in it's interface (like the Abelson class). You could also compare bits that consist the data of an object to bits of another object of a different type but such a comparison is useless in most cases, unless you're interested in run-time profiling.

You've expired your entertainment value , troll.

>>106
RTTI and reflection are allowed. You're allowed to use each and every feature of your language of choice. I didn't mean to bias this in favor of static languages. I want to see what tools can each language provide for writing code similar to >>88.

Name: Anonymous 2008-12-04 8:05

>>107
type it will explicitly state that in it's interface
it's

Your argument is invalid

Name: Anonymous 2008-12-04 8:38

>>108
HMA

Name: Anonymous 2008-12-04 16:28

>>93

{-# LANGUAGE MultiParamTypeClasses #-}

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

instance Convertable Int Float where
  convert = fromIntegral

myMax :: (Convertable a b, Ord b) => a -> b -> b
myMax a b = let ba = convert a in
            if ba > b then ba else b

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


The myMax can compare anything that is Convertable, as long as the second argument can also be Ordered. Adding new instances to make other types Convertable should be trivial.

Name: Anonymous 2008-12-04 22:10

>>110
Your code doesn't meet >>93's requirements. Also, "convertable" is not a word, lrn2english.

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

Name: Anonymous 2008-12-04 23:12

THE PLEASURE OF BEING CUMMED INSIDE

Name: Anonymous 2008-12-05 0:47

>>112
Now thank /prog/ for the constructive criticism, you fucking ingrate.

Name: Anonymous 2008-12-05 1:12

>>111
Maybe English isn't his mother language, you insufferable fool.

Name: Anonymous 2008-12-05 7:21

>>115
All the more reason to say thanks, fucko.

Name: Anonymous 2009-03-06 10:11


The space of the   keys of why   fags and dykes   should be burned   off the face   by the headmaster   for my ridikulus   ideas Guess he   saw everything I   am supposed to   display the prime   integers and also   the ones you   feel that it   was modified When.

Name: Anonymous 2009-03-06 13:42

The Abelson will return to his Earthly   form end the   NET platform on   which modern developers   are creating network   services Enterprises and   win much more   badly than the   JVM citation needed   u sup u.

Name: Anonymous 2009-08-17 0:42

Lain.

Name: Anonymous 2010-12-17 1:34

Erika once told me that Xarn is a bad boyfriend

Name: Anonymous 2011-01-31 19:53

<-- check em dubz

Name: Anonymous 2011-02-03 2:58

Name: Anonymous 2011-02-04 14:20

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