Haskell 如何生成随机集?(哈斯克尔)
以下是如何定义集合:Haskell 如何生成随机集?(哈斯克尔),haskell,Haskell,以下是如何定义集合: module SetOrd (Set(..),emptySet,isEmpty,inSet,subSet,insertSet, deleteSet,powerSet,takeSet,(!!!),list2set,unionSet) where import Data.List (sort) {-- Sets implemented as ordered lists without duplicates --} newtype Set a
module SetOrd (Set(..),emptySet,isEmpty,inSet,subSet,insertSet,
deleteSet,powerSet,takeSet,(!!!),list2set,unionSet)
where
import Data.List (sort)
{-- Sets implemented as ordered lists without duplicates --}
newtype Set a = Set [a] deriving (Eq,Ord)
instance (Show a) => Show (Set a) where
showsPrec _ (Set s) str = showSet s str
showSet [] str = showString "{}" str
showSet (x:xs) str = showChar '{' ( shows x ( showl xs str))
where showl [] str = showChar '}' str
showl (x:xs) str = showChar ',' (shows x (showl xs str))
然后我想系统生成一个随机集,如:
getSetInt :: IO Set
getSetInt = do
d <- getRandomInt 10
n <- getRandomInt 5
m <- getRandomInt 5
getSetI d n m
getSetI :: Int -> Int -> Int -> IO Set
getSetI _ _ 0 = return (Set [])
getSetI d n m = do
f <- getRandomSet d n
fs <- getSetI d n (m-1)
return (Set (f:fs))
getRandomSet :: Int -> Int -> IO Set
getRandomSet _ 0 = return (Set [])
getRandomSet d n = do
f <- getRandomInt d
fs <- getRandomSet d (n-1)
return (Set (f:fs))
getSetInt::IO集
getSetInt=do
d IO集
getSetI u0=返回(Set[])
getSetI d n m=do
f IO集
getRandomSet 0=返回(集合[])
getRandomSet d n=do
f第一个问题
您的集合定义为
newtype Set a = ...
这意味着Set
具有种类*->*
,换句话说,您需要向其传递一个类型,以便对其进行参数化
想一想
template<typename T>
class foo{};
代码的其余部分
接下来在getSetI
中,行
fs <- getSetI d n (m-1)
从随机
包中
其余的代码实际上包含了大约10-12个错误,所以我不打算在这里描述每一个错误。主要是
return Set foo
错误,这将传递return
2个参数,您需要
return (Set foo)
另外,getSetI
似乎会生成m
随机集,然后尝试将它们组合成一个IO(Set(Set Int))
,你到底想做什么?哦!谢谢!!我现在明白了。哈斯凯尔对我来说太难了。@zll19910516很乐意帮忙,祝哈斯凯尔好运!别担心,每个人一开始都有麻烦
getRandomInt a = randomRIO (0, a)
return Set foo
return (Set foo)