mardi 5 novembre 2019

Problems to make a function that rollsNDice in Haskell

I'm experimenting with randomness in Haskell and I wanted to do a function that given an Int n returns a list of states of random numbers between 1 and 6:

-- auxiliar function
rollDie :: State StdGen Int
rollDie = do generator <- get
                let (value, newGenerator) = randomR (1,6) generator
                put newGenerator
                return value

rollNDice :: Int -> State StdGen [Int]
rollNDice n | n == 0    = [] :: State StdGen [Int]
  | otherwise = (:) <$> rollDie <*> rollNDice (n-1)

but when I try to run it in ghci I get:

Couldn't match type ‘[a0]’
                     with ‘StateT StdGen Data.Functor.Identity.Identity [Int]’
      Expected type: State StdGen [Int]
        Actual type: [a0]
    • In the expression: [] :: State StdGen [Int]
      In an equation for ‘rollNDice’:
          rollNDice n
            | n == 0 = [] :: State StdGen [Int]
            | otherwise = (:) <$> rollDie <*> rollNDice (n - 1)

I don't understand the error. Any ideas?




Aucun commentaire:

Enregistrer un commentaire