Why do I end up with "binding" errors in the following program?
wheels :: Int
cars :: Int
carpark wheels cars
| wheels == odd = error wheels "is not even"
| cars <= 0 = error cars "is an invalid number"
| (2*cars) >= wheels = error "the number of wheels is invalid"
| wheels >= (4*cars) = error "the number of wheels is invalid"
| otherwise = "There are " (wheels-(2 * cars)) `div` 2 "cars and " (cars - ((wheels - (2 * cars)) div 2)) "motorcycles on the parking lot"
This is the error:
aufgabe1.lhs:6:3: The type signature for ‘wheels’ lacks an accompanying binding aufgabe1.lhs:7:3: The type signature for ‘cars’ lacks an accompanying binding
How can I get rid of it?
There are many problems with your program, but lets focus on the "binding" one first. You're probably accustomed to Pascal or C, where you have to specify the type of the argument at the argument:
string carpark(int wheels, int cars);
However, Haskell doesn't work like this. If you write
wheels :: Int
in your document, you're telling the compiler that the value wheels
will have the type Int
. The compiler now expects a definition somewhere. This definition—it's binding—is missing. The type of wheels
is known, but it's not known what value wheels
should be bound to.
If you were to add
wheels = 1 * 2 + 12312
the compiler wouldn't complain about that particular binding anymore.
As I've conclused above, you want to specify the arguments' types of carpark
, right? However, this concludes that you specify carpark
's type:
carpark :: Int -> Int -> String
carpark wheels cars
| -- omitted
This will get rid of the "missing bindings" errors.
Well, after this, you will still have a non-compiling piece of software, for example error wheels "is not even"
isn't valid. Have a look at error
's type:
error :: String -> a
Since wheels
isn't a String
, this won't compile. Instead, you have to show
wheels
:
error (show wheels ++ " is not even")
Note that error (show wheels) " is not even"
will happily compile, but won't give you the error message you're actually looking for, so beware of parenthesis and string concatenation.
Write a function whatNumber
that returns "Is Odd" if the number is odd and "Is Even" if the number is even, e.g.
whatNumber 2 == "Is Even"
Write a function whatNumberId
, that returns "<x> is odd"
if the number is odd and "<x> is even"
if the number is even, where <x>
should be the number, e.g.
whatNumberId 123 == "123 is odd"
Both exercises should help you to accomplish your original task.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With