首页 > 解决方案 > 如何在haskell中调用函数?

问题描述

我有一个创建列表然后随机播放的代码。但我无法执行,因为=main = do部分中的问题。错误是"parse error on input"

这是代码:

import System.IO
import System.Random

shuffle :: [a] -> [a]
shuffle list = if length list < 2 then return list else do
i <- randomRIO (0, length list-1)
r <- shuffle (take i list ++ drop (i+1) list)
return (list!!i : r)

main = do  --the problem is in this line
   putStrLn "Enter the number:"  
   number <- getLine  
   let n = (read number :: Int)
   let list = [1..n]
   print list
   shuffle list

标签: haskellrandomiomainshuffle

解决方案


调用函数不是问题。您的定义有缩进问题,这对解析器shuffle来说不是问题,直到它到达该行。main = do

import System.IO
import System.Random

shuffle :: [a] -> IO [a]
shuffle list = if length list < 2 then return list else do
   i <- randomRIO (0, length list-1)
   r <- shuffle (take i list ++ drop (i+1) list)
   return (list!!i : r)

main = do  --the problem is in this line
   putStrLn "Enter the number:"  
   number <- getLine  
   let n = (read number :: Int)
   let list = [1..n]
   print list
   shuffled <- shuffle list
   print shuffled

请注意正确使用的其他更改IO


推荐阅读