我试图在一些数据结构中存储随机生成的骰子值,但不知道在Haskell中如何准确地执行它.到目前为止,我只能生成随机整数,但我希望能够将它们与相应的颜色值进行比较并存储颜色(不能真正设想函数的外观).这是我的代码 -
module Main where
import System.IO
import System.Random
import Data.List
diceColor = [("Black",1),("Green",2),("Purple",3),("Red",4),("White",5),("Yellow",6)]
diceRoll = []
rand :: Int -> [Int] -> IO ()
rand n rlst = do
num <- randomRIO (1::Int, 6)
if n == 0
then printList rlst -- here is where I need to do something to store the values
else rand (n-1) (num:rlst)
printList x = putStrLn (show (sort x))
--matchColor x = doSomething()
main :: IO ()
main = do
--hSetBuffering stdin LineBuffering …Run Code Online (Sandbox Code Playgroud) 我曾尝试编写一个函数来执行此操作,但无法让GHCI理解我的代码.我来自OOP背景,所以函数式编程对我来说是一个全新的领域.
checkPigLatin :: String -> String
checkPigLatin sentence (x:xs)
| check == "true" = "This is Pig Latin"
| otherwise = "Not Pig Latin"
where check = if (x `elem` "aeiouAEIOU", '-' `elem` xs, snd(break('a'==) xs) == 'a', snd(break('a'==) xs) == 'y') then "true"
Run Code Online (Sandbox Code Playgroud) 我正在尝试为用户播放的每个卷发出随机生成的骰子.用户每回合有3个卷,他可以玩5个回合(我还没有实现这个部分,我会很感激建议).
我也想知道如何随机显示颜色.我有元组列表,但我认为我需要一些使用随机和该列表来匹配这些颜色的函数.我正在努力如何.
module Main where
import System.IO
import System.Random
import Data.List
diceColor = [("Black",1),("Green",2),("Purple",3),("Red",4),("White",5),("Yellow",6)]
{-
randomList :: (RandomGen g) -> Int -> g -> [Integer]
random 0 _ = []
randomList n generator = r : randomList (n-1) newGenerator
where (r, newGenerator) = randomR (1, 6) generator
-}
rand :: Int -> [Int] -> IO ()
rand n rlst = do
num <- randomRIO (1::Int, 6)
if n == 0
then doSomething rlst
else rand (n-1) (num:rlst)
doSomething x = …Run Code Online (Sandbox Code Playgroud)