Q) Write two different functions maximum1 and maximum2 that compute the maximum of three numbers. The built in max functions can't be used
I have the following code, would this be considered computationally different?
maximum1:: Int->Int->Int->Int
maximum1 x y z| x> y && x> z = x
|y>x && y>z =y
| otherwise =z
maximum2::Int->Int->Int->Int
maximum2 x y z= head [k | k<-[x,y,z], k>x && k>y || k>x && k>z || k>y && k>z]
CodePudding user response:
The first one is better, because it does not need lists, no filters and no head. This, if not properly optimized by the compiler, will lead to inefficient code, in regards of memory usage and speed. If you actually have the need of a function that takes exactly three arguments, your first solution is desirable. If you have a list of values, you could use the following function.
maxl :: (Foldable t, Ord b, Bounded b) => t b -> b
maxL = foldl max minBound
CodePudding user response:
maximum1:: Int->Int->Int->Int
maximum1 x y z| x>= y && x>= z = x
|y>=x && y>=z =y
| otherwise =z
maximum2:: Int->Int->Int->Int
maximum2 x y z| x-y>=0 && x-z>=0 = x
|y-x>=0 && y-z>=0 =y
|otherwise =z
