1
lol :: IO int
lol = go -1 0 0 0
where go k m n p = case k of
        -1 -> do{
                q <- readLn ;
                go 0 0 0 q
            }
        p -> do{
                putStrLn $ show $ n
            }
        _ -> do{
                q <- readLn ;
                go (k+1) q (if q > m then n+q-m else n) p
                return()
            }

I(a haskell beginner) am doing some practise questions. I have written a recursive function but i don't know how to use it in main. Please help me to do solve this problem. This is my idea in C++ and I got it accepted.

#include<iostream>
using namespace std;
int main(){
    long long int prev=0;
    long long int count,ans=0;
    cin >> count;
    long long int p;
    for(int i=0; i<count ;i++){
        cin >> p;
        if(p>prev){
            ans+=p-prev;
        }
        prev=p;
    }
    cout << ans << endl;
}
1
  • 3
    What's the purpose of the function? Explain. In Haskell, recursive functions usually require at least two parameters where there's the head, and the tail of a set of elements. Commented Feb 12, 2016 at 3:07

2 Answers 2

2

There are several syntax errors:

  • add parentheses around negative numbers when using them as arguments
  • to avoid starting a fresh line in the module block, indent where (and all following lines) a little bit
  • add the missing semicolon to the line before return ()

And one type error: you should write lol :: IO (). After fixing these, you may write main = lol to use it (or simply name it main instead of lol). No idea whether it does what it's supposed to do, but that seems like a thing you should be able to test once you get it running.

Sign up to request clarification or add additional context in comments.

Comments

2

How about this. I just translated it directly from C++

module Main where


go :: Int -> Int -> Int -> IO Int
go i prev acc
  | i > 0   = do p <- readLn
                 if p > prev
                   then go (i-1) p (acc + (p - prev))
                   else go (i-1) p acc
  | otherwise = return acc

main :: IO ()
main = do
  count <- readLn :: IO Int
  ans <- go count 0 0
  print ans

4 Comments

The way you use fmap there will pile up a bunch of "stack". You should make ans an argument to go (and make it strict). Or use StateT or (less efficient) an IORef.
@dfeuer, since you ask :) I did not make acc strict, after all, we are striking for clarity hear, not performance.
With BangPatterns, that's as simple as go i prev !acc = .... But I guess you don't feel like a language pragma.
@dfeuer Precisely. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.