2015-09-09 21 views
0

我想獲得一個函數,返回一列零或清單,顯然是以隨機的方式。數字列表的隨機二進制列表

例子:

getBinaryRandomList::Int->Int->[[Int]] 

Prelude> getBinaryRandomList 4 3 
[[1,0,0,1],[1,1,0,1],[0,0,0,1], [0,1,0,1]] 

到目前爲止,我已經做到了這一點功能:

--tuns an `Int` into a `[Int]`. The [Int] would represent a binary number 
int2bin :: Int -> [Int] 
int2bin 0 = [] 
int2bin n = mod n 2 : int2bin (div n 2) 

我已經來到這裏卡住了,它拋出在編譯時錯誤:

--returns a random number 
import System.Random 
randomInt::(Int,Int)->Int 
randomInt x y = do 
       newStdGen 
       randomR(x, y) getStdGen 

編譯...

[1 of 1] Compiling Main    (ag.hs, interpreted) 

ag.hs:8:25: parse error on input `randomR' 

「主」功能會是這樣的:

--n lists number 
--d digit number 
getBinaryRandomList::Int->Int->[[Int]] 
getBinaryRandomList d 0 = [] 
getBinaryRandomList d n = take d (int2bin(randomInt(0,50))) : getBinaryRandomList(n-1) 

我的做法是下一個:

  1. 編碼創建0的n之間的偶然詮釋數的函數。
randomInt::(Int,Int)->Int 
  • 編碼,這些偶然的號碼轉換成二進制文件的列表的功能。
  • int2bin::Int->[Int] % Already done 
    
  • 形成與這些數字
  • getBinaryRandomList::Int->Int->[[Int]] 
    

    我怎麼能實現在Haskell的列表?

    +3

    功能是確定性的,不能給你一個隨機值。你的'randomInt'操作需要一個種子,發生器或者擁有'IO'。 –

    回答

    1

    正如在評論中指出,你不能創建一個沒有IO一個StdGen,但你可以在你的主函數創建一個並將其傳遞的參數傳遞給randomInt功能,通過這種方式:

    import System.Random 
    
    main = do 
        a <- newStdGen 
        putStrLn . show . randomInt 0 1 $ a 
    
    randomInt:: Int -> Int -> StdGen -> (Int, StdGen) 
    randomInt x y s = do 
          randomR (x, y) s 
    

    您得到的有關RandomR的錯誤消息是由於未導入System.Random引起的。

    我希望這會有所幫助。

    +0

    實際上,從概念上講:您可以在純代碼中的任何位置獲取/創建「StdGen」或任何其他「IO a」值 - 您只是無法告訴實際運行時IO系統實際執行它(安全地):) –

    +0

    @ ErikAllik好點! – fgv

    +0

    對不起,我犯了一個錯誤,我忘了複製巫婆System.Random中的代碼行已導入。我會編輯它。謝謝 – Hernan