[Haskell-beginners] function not working as expected, type issues

David McBride toad3k at gmail.com
Wed Apr 9 06:17:12 UTC 2014


I didn't look closely enough at what you wrote, you had several issues.
Let me try again:

displayD :: String -> Int -> IO ()
displayD string 0 = return ()
displayD string count = do
  hPutStr stdout string
  displayD string (count - 1)

This is one way to do it.  You use the arguments themselves.  Obviously
this won't work with negative counts.

displayD :: String -> Int -> IO ()
displayD string count
  | count <= 0 = return ()
  | otherwise = do
      hPutStr stdout string
      displayD string (count - 1)

And as for figuring out types.  You should try to load your source file in
ghci, and then use the :t and :i commands liberally to inspect functions
you are using.  You will begin to get the hang of it in no time.


On Wed, Apr 9, 2014 at 2:08 AM, David McBride <toad3k at gmail.com> wrote:

> Try using guards:
>
> displayD :: IO () -> String -> Int
> displayD string count =
>         | count > 0 = hPutStr stdout string
>         | otherwise = displayD string (count - 1)
>
> Alternatively use if, then, else.
>
>
>
> On Wed, Apr 9, 2014 at 2:03 AM, Alexej Magura <sickhadas at gmail.com> wrote:
>
>> K, so I have a function that I'm writing that takes a *string* and a
>> *count* and prints the *string* to STDOUT *count* times:
>>
>> displayD :: IO () -> String -> Int
>> displayD string count = do
>>         (count > 0) && hPutStr stdout string
>>         (count > 0) && displayD string (count - 1)
>>
>> However, when I try to compile the file, I get several errors; here's a
>> pastebin: http://pastebin.com/DEsuAvfz
>>
>> What I'm trying to do here is check to see if *count* is greater than 0,
>> and then if it is, then I'd like to print *string* to STDOUT until *count*
>> equals 0.  I tried doing it via pattern matching, like so:
>>
>> displayD string (count > 0) = do
>>
>> But I haven't seen any examples of how to do pattern matching in
>> functions using *do*, that is *IO*, so I'm unsure if the above is even
>> anywhere near correct.
>>
>> Still very uncomfortable with declaring function types: I have a hard
>> time figuring out which type is returned and what type is expected as an
>> arg.  My initial guess is that the *first* type specified is the one
>> returned, but I'm not sure.
>>
>> --
>> Alexej Magura
>> Sent with Airmail
>> _______________________________________________
>> Beginners mailing list
>> Beginners at haskell.org
>> http://www.haskell.org/mailman/listinfo/beginners
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20140409/ddc72096/attachment.html>


More information about the Beginners mailing list