简体   繁体   English

Haskell输入列表-列表递归

[英]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] 当我在控制台divv 10中写入内容时,我会得到列表[10..2]
When i write qsort[1,2,8,5,3,9,0] i'll get the list sorted. 当我写qsort [1,2,8,5,3,9,0]时,我将对列表进行排序。

I want the user to give just a number for example 100 and then to call qsort (divv 100). 我希望用户仅给出一个数字,例如100,然后调用qsort(divv 100)。 How can i make this ? 我该怎么做?

Thanks in advance 提前致谢

To read input from terminal, you can use getLine :: IO String . 要从终端读取输入,可以使用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 ). 但是,在将字符串传递给函数之前,您需要将其转换为整数类型(在本例中为Int )。 You can do this using the function read :: Read a => String -> a . 您可以使用read :: Read a => String -> a来执行此操作。 To print a string, you can use the function putStrLn :: String -> IO () . 要打印字符串,可以使用功能putStrLn :: String -> IO () Before printing qsort (divv n) , however, you will need to convert its result into a string. 但是,在打印qsort (divv n)之前,您需要将其结果转换为字符串。 This is done using the function show :: Show a => a -> String . 使用功能show :: Show a => a -> String

Putting everything together, you first want to getLine a string, say s . 将所有内容放在一起,你首先要getLine字符串,说s Next, you want to read that string into an Int , say n . 接下来,您想将该字符串readInt ,例如n Finally, you want to use putStrLn to print the result of calling show on the list qsort (divv n) . 最后,您要使用putStrLn在列表qsort (divv n)上打印调用show的结果。 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 ). 为了对这些动作进行排序 ,您将需要在IO monad中执行bind操作,否则do符号(这只是对诸如bind monadic组合符不满意)。 Here is an example implementation. 这是一个示例实现。 As an exercise, try translating this implementation into do notation: 作为练习,请尝试将此实现转换为do表示法:

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

Note that your implementation of divv is incorrect. 请注意,您的divv实现不正确。 It should read divv n = [n,n-1..2] (in order to generate a list of integers from n to 2 in descending order). 它应读取divv n = [n,n-1..2] (以便按降序生成从n2的整数列表)。 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. 但是我认为这是最简单的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM