[英]Mapping function to list/array in haskell?
I am trying to initiate a random array to begin the game. 我正在尝试启动一个随机数组来开始游戏。 To do that I create a function randomBoard which returns '*' or ' ' to represent a space on the game board.
为此,我创建了一个函数randomBoard,它返回'*'或''来表示游戏板上的空格。
I want to be able to create the game board array with this function. 我希望能够使用此功能创建游戏板阵列。 I havent been able to succesfully instantiate an array yet.
我还没能成功实例化一个数组。 I am hoping there is a way i can declare an array of say size 100 and use my random function to set each element.
我希望有一种方法可以声明一个大小为100的数组并使用我的随机函数来设置每个元素。
This obviously doesnt work or even compile. 这显然不起作用甚至编译。 I am sure there are a couple things wrong with it, as I am not sure really how to even work with IO in haskell and produce this outcome.
我确信它有一些问题,因为我不确定如何在haskell中使用IO并产生这种结果。 Any guidance is much appreciated...
任何指导都非常感谢...
This should work for you: 这应该适合你:
import Control.Monad
import System.Random
import Data.Array
import Data.List
randomBoard :: IO Char
randomBoard =
do
f1 <- randomIO :: IO Int
if(f1 `mod` 2) == 0
then return '*'
else return ' '
boardArray :: IO (Array Int Char)
boardArray = listArray (0, 99) <$> replicateM 100 randomBoard
Here's what I changed: 这是我改变的:
randomBoard :: IO Char
for clarity. randomBoard :: IO Char
。 (The code would still work without it, as Haskell correctly infers this type if you don't supply it.) boardArray
to use IO
. boardArray
的类型以使用IO
。 Anything that uses IO
, no matter how indirectly, need to be in IO
itself. IO
东西,无论多么间接,都需要在IO
本身。 listArray (0, 100)
to listArray (0, 99)
, as the former would actually be 101 elements. listArray (0, 100)
更改为listArray (0, 100)
listArray (0, 99)
,因为前者实际上是101个元素。 map randomBoard $ 100 (0,100)
isn't right at all. map randomBoard $ 100 (0,100)
根本不对。 To get a list of several of the same thing, you'd usually use replicate
, but since the thing you care about here is in the IO
monad, you use replicateM
instead. replicate
,但由于您关心的事情是在IO
monad中,因此您使用replicateM
。 replicateM 100 randomBoard
gives an IO [Char]
with 100 random elements of either '*'
or ' '
. replicateM 100 randomBoard
给出一个带有100个'*'
或' '
随机元素的IO [Char]
。 Control.Monad
, which is needed to use replicateM
. Control.Monad
的导入,这是使用replicateM
所必需的。 <$>
in boardArray
. boardArray
使用<$>
。 Since you want to call listArray
with a [Char]
and get an Array Int Char
, but replicateM 100 randomBoard
is an IO [Char]
, you can't just apply the argument directly. [Char]
调用listArray
并得到一个Array Int Char
,但是replicateM 100 randomBoard
是一个IO [Char]
,你不能直接应用这个参数。 Using <$>
(which is also called fmap
) applies it "inside" of IO
, giving you back an IO (Array Int Char)
. <$>
(也称为fmap
)将其应用于IO
“内部”,返回IO (Array Int Char)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.