开发者

Haskell counting example

emptyAndOther
    :: IO (Int, Int)
emptyAndOther =
   do
     c <- getChar
     if c == '\ESC'
              then return (x, y)
     else if isSpace c
              then (x+1) y
     else x (y+1)
  where
     x = 0
     y = 0

What is wrong with this code? I want to count every empty line and every char and on ESC button, return the re开发者_开发技巧sult.

Dont seem to understand, what is wrong

yes, i must use this signature


The problem lies in the fact that your else branches are attempting to call x as a function, which is a weird thing to do, since it's a number instead. I suggest trying to write a helper function

emptyAndOther' :: Int -> Int -> IO (Int, Int)

such that emptyAndOther = emptyAndOther' 0 0. For the future, I would point out that carefully reading error messages helps a lot. For example, GHC's error message says almost exactly what I did (though in terser language):

The function `x + 1' is applied to one argument,
but its type `Int' has none
In the expression: (x + 1) y


Here's a question in response. In the code:

 else if isSpace c
          then (x+1) y
 else x (y+1)

What do the expressions (x+1) y and x (y+1) mean? I'm guessing you're trying to increment x and y, but haskell doesn't work that way.

Instead, try having emptyAndOther take the current value of x and y, and then recurse in those two cases by calling emptyAndOther (x+1) y or emptyAndOther x (y+1).


Your function has return type IO (Int,Int) Now lets see the 3 branches in if/else

If part results in return (x, y) which is good as this will return a IO (Int,Int) and thats what your function return type is

Now in the else if and else part, the result seems to doesn't imply with the fact that your function return type is IO (Int,Int) .

Both the else if and else expressions should result in IO (Int,Int) type. This is just a hint. If you have worked in other programming language like C# and Java and try to write a function which return a string but in if part you return string and in else part you return int. That won't work .. same problem applies here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜