我最近开始学习Haskell。我正在尝试编写一个程序,从数组中随机选择一个元素:
import System.Random
randomInt :: (Int, Int) -> IO Int
randomInt range = randomRIO range :: IO Int
choseRandom :: [a] -> a
choseRandom list =
length list
>>=
(\l -> randomInt(0,l-1))
>>=
(\num -> (list !! num))
main :: IO ()
main = undefined
我遇到了以下错误:
Build FAILED
C:\Users\User\Haskell\Real\src\Main.hs: line 7, column 9:
Couldn't match expected type `IO Int' with actual type `Int'
In the return type of a call of `length'
In the first argument of `(>>=)', namely `length list'
In the first argument of `(>>=)', namely
`length list >>= (\ l -> randomInt (0, l - 1))'
我做错了什么?对于初学者来说,处理单子很困难。
fmap
的概念,丑陋的(\num -> (list !! num))
就可以简写为(list !!)
。 - Ingo