【问题标题】:How to call a function in haskell?如何在haskell中调用函数?
【发布时间】:2020-11-27 06:09:01
【问题描述】:

我有一个代码可以创建一个列表然后随机播放它。但我无法执行,因为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

【问题讨论】:

  • do 中的shuffle 没有多大意义。列表确实是 monad 类型类的一个实例,但这里return 是一个列表,所以基本上这是列表中的一个列表。
  • 除非你的函数返回IO someType,否则你不能做IO。此外,您在main 中忽略了shuffle list 的结果,因此您不会看到任何打乱的列表。可能还有其他问题。
  • 我已回滚您的编辑,因为它们已使现有答案无效。如果您对新修改的代码有新问题,请发布一个新问题,如有必要,可能包括返回此问题的链接作为背景。

标签: haskell random io main shuffle


【解决方案1】:

调用函数不是问题。您对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

【讨论】:

  • 我完全按照您所说的进行了更改,但之后我认为数据类型还有 2 个问题
猜你喜欢
  • 1970-01-01
  • 2022-10-01
  • 1970-01-01
  • 2015-06-25
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多