user3358377
user3358377

Reputation: 145

Haskell input list - recursive on list

i want the user to give the size of the list and then use that list in other function. Something like that

divv x = [x..2]

qsort       :: [Int] -> [Int]    
qsort []     = []    
qsort (x:xs) =    
   qsort smaller ++ [x] ++ qsort larger    
   where    
      smaller = [a | a <- xs, a <= x]    
      larger  = [b | b <- xs, b > x]  

When i write in the console divv 10 i'll get the list [10..2]
When i write qsort[1,2,8,5,3,9,0] i'll get the list sorted.

I want the user to give just a number for example 100 and then to call qsort (divv 100). How can i make this ?

Thanks in advance

Upvotes: 0

Views: 415

Answers (1)

emi
emi

Reputation: 5410

To read input from terminal, you can use getLine :: IO String. Before passing the string to your function, however, you will need to convert it into an integral type (in this case, an Int). You can do this using the function read :: Read a => String -> a. To print a string, you can use the function putStrLn :: String -> IO (). Before printing qsort (divv n), however, you will need to convert its result into a string. This is done using the function show :: Show a => a -> String.

Putting everything together, you first want to getLine a string, say s. Next, you want to read that string into an Int, say n. Finally, you want to use putStrLn to print the result of calling show on the list qsort (divv n). In order to sequence these actions, you will require the bind operation in the IO monad, or else do notation (which just desugars to monadic combinators like bind). Here is an example implementation. As an exercise, try translating this implementation into do notation:

sortList :: IO ()
sortList = fmap read getLine >>= putStrLn . show . qsort . divv

Note that your implementation of divv is incorrect. It should read divv n = [n,n-1..2] (in order to generate a list of integers from n to 2 in descending order). Also note that there are probably better ways to accomplish the task of asking a user for input, and returning the result of applying that input to some function. But this is the easiest, in my opinion.

Upvotes: 1

Related Questions