I’m learning Haskell, and these are my first steps in trying to understand the syntax. I’m having a very hard time, and the language reference is not helpful, unfortunately.
I tried to do :type (line_length 1 2 3 4) and I have red the reference on printf However, it uses symbols with vague meaning instead of words. So, I’m stuck and asking for help.
Put simple: what do I write in place of ???.
line_length :: Integer -> Integer -> Integer -> Integer -> ???
line_length ax ay bx by =
printf ("The length of the line between the points" ++
"(%d,%d) and (%d,%d) is %.5f\n") ax ay bx by
((((fromIntegral (ax - bx)) ** 2.0) +
((fromIntegral (ay - by))) ** 2.0) ** 0.5)
The overloaded return type of
printf :: PrintfType r => String -> rcan be a little confusing, but it helps to look at thePrintfTypeinstances which are available:First, we have this instance:
This one is used to allow
printfto take a variable number of arguments. This makes sense due to currying, but you probably won’t think of it as the “true” return type of the function. For more information about how this works, see How does printf work in Haskell?.Then we have this instance,
This means that we can use it as an
IOaction. Similar toprint, this will print the result to standard output. The result of the action isundefined, so you should just ignore it.1And finally,
The type class here is mostly to allow this to be Haskell 98 compliant. Since the only instance of
IsCharisChar, you can think of this asbut that would require the GHC-specific extension
FlexibleInstances.What this instance means is that you can also just return a
Stringwithout printing it, similar tosprintfin C.So depending on whether you want to print the result or just return it, you can replace
???with eitherIO ()orStringin your example.However, there is another problem with your code in that the compiler is unable to determine which type you wanted the last argument to be, so you have to help it out with a type annotation:
1 This is done to avoid extensions. With extensions, we could write
instance PrintfType (IO ())and the result would be().