[Haskell-cafe] Problems with function recursion in Haskell

Sumit Sahrawat, Maths & Computing, IIT (BHU) sumit.sahrawat.apm13 at iitbhu.ac.in
Mon May 9 13:53:10 UTC 2016


Hi,

Rather than using indexing, or using head, I recommend using pattern
matching. These functions are not total, i.e. they fail to provide a valid
result for some specific inputs, like head on empty list.

The following is similar to replicateM from Control.Monad, you can either
modify it to suit your need, or use replicateM combined with map to turn a
list of Strings to a list of IO () as required by replicateM.

    execNTimes :: Int -> [IO ()] -> IO ()
    execNTimes 0 [] = return ()
    execNTimes n (x : xs)
      | n <= 0    = return ()
      | otherwise = x >> execNTimes (n - 1) xs

Where, the following are equivalent:

    a >> b == do a
                 b

Regards,
  Sumit

On 9 May 2016 at 19:00, Henson <jfsihenson at gmail.com> wrote:

> Hi,
>
> I'm new in Haskell and I need help in recursion.
> That function below is returning "*** Exception: Prelude.head: empty list"
> and
> I need resolve that:
> execNTimes 0 [] = return()
> execNTimes n xs = if n<=0  || null xs
>     then return()
>     else do
>         si <- getLine
>         let s = words si
>             l = read (s !! 1) :: Int
>             r = read (s !! 2) :: Int
>         if head s=="Q"
>             then do
>                 let z = slice l r xs
>                     m = foldl lcm 1 z
>                 print (m `mod` (toInteger 1000000007))
>             else do
>                 let s1 = update l r xs
>                 execNTimes (n-1) s1
>         execNTimes (n-1) xs
>
>  Anybody can me help?
>
> Thank you,
> Josenildo Silva
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20160509/6f03ac70/attachment.html>


More information about the Haskell-Cafe mailing list