[Haskell-cafe] Problems with function recursion in Haskell

Jonne Ransijn yoyoyonny at gmail.com
Mon May 9 15:05:09 UTC 2016


Hi Josenildo.

I would personally rewrite your code to something like this:

import Data.Maybe (fromMaybe)
import System.IO (hFlush, stdout)
import Text.Read (readMaybe)

readDef :: a -> String -> a
readDef def = fromMaybe def . readMaybe

isAtLeast :: [a] -> Int -> Bool
isAtLeast ls n
    | n <= 0  = True
    | null ls = False
    | otherwise = isAtLeast ls (n-1)

execNTimes :: Int -> [a] -> IO ()
execNTimes n lst
    | n <= 0 = return()
    | do
        (from, to, quit) <- getCmds
        if quit
            then let z = slice from to xs
                     m = foldl lcm 1 z in
                print $ m `mod` modVal
            else execNTimes (n-1) $ update from to lst
        execNTimes (n-1) lst
  where
    modVal :: Integer
    modVal = 1000000007
    getCmds :: IO (Int, Int, Bool)
    getCmds = do
        putStr "Enter command: "
        hFlush stdout
        cmds <- words <$> getLine
        if not $ cmds `isAtLeast` 3
            then do
                putStrLn "Too few commands"
                getCmds
            else let from = readDef 0 (cmds !! 1) :: Int
                     to   = readDef 0 (cmds !! 2) :: Int
                     quit = head cmds == "Q" in
                if from < 0 || to >= length lst || from > to
                    then do
                        putStrLn "Invalid range"
                        getCmds
                     else (from, to, quit)

Do note that the above code is untested, and that it's written on a mobile
phone.

I don't know what your intentions with the code are, so I added some error
messages and variable names that you might want to change.

About 'xs':
xs is frequently used to mean "rest of list". I would recommend using ls or
lst instead to name the whole list.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20160509/8c77c5b2/attachment.html>


More information about the Haskell-Cafe mailing list