[Haskell-cafe] Problems with function recursion in Haskell
yoyoyonny at gmail.com
Mon May 9 15:05:09 UTC 2016
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()
(from, to, quit) <- getCmds
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
modVal :: Integer
modVal = 1000000007
getCmds :: IO (Int, Int, Bool)
getCmds = do
putStr "Enter command: "
cmds <- words <$> getLine
if not $ cmds `isAtLeast` 3
putStrLn "Too few commands"
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
putStrLn "Invalid range"
else (from, to, quit)
Do note that the above code is untested, and that it's written on a mobile
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.
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...
More information about the Haskell-Cafe