将函数映射到haskell中的列表/数组? [英] Mapping function to list/array in haskell?
问题描述
我正在尝试启动随机数组以开始游戏.为此,我创建了一个函数randomBoard,该函数返回'*'或''代表游戏板上的空间.
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.
我希望能够使用此功能创建游戏板阵列.我还没有成功实例化一个数组.我希望有一种方法可以声明一个大小为100的数组,并使用我的随机函数设置每个元素.
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.
这显然行不通甚至无法编译.我肯定这有一些问题,因为我不确定如何在Haskell中甚至与IO一起工作并产生这种结果.任何指导都将不胜感激...
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. Any guidance is much appreciated...
推荐答案
这应该对您有用:
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
这就是我更改的内容:
- 为清楚起见,我添加了类型签名
randomBoard :: IO Char
. (如果没有它,代码仍然可以工作,因为如果您不提供它,Haskell会正确推断出这种类型.) - 我将
boardArray
的类型更改为使用IO
.任何使用IO
的东西,无论多么间接,都必须存在于IO
本身. - 我将
listArray (0, 100)
更改为listArray (0, 99)
,因为前者实际上是101个元素. -
map randomBoard $ 100 (0,100)
根本不正确.要获取多个相同事物的列表,通常使用replicate
,但是由于您在此关心的事物位于IO
monad中,因此请改为使用replicateM
.replicateM 100 randomBoard
给出一个IO [Char]
,其中包含100个'*'
或' '
随机元素. - 我添加了
Control.Monad
的导入,使用replicateM
需要此导入. - 我在
boardArray
中使用<$>
.由于要使用[Char]
调用listArray
并获得Array Int Char
,但是replicateM 100 randomBoard
是IO [Char]
,因此不能直接应用该参数.使用<$>
(也称为fmap
)将其应用到IO
的内部",为您提供IO (Array Int Char)
.
- I added the type signature
randomBoard :: IO Char
for clarity. (The code would still work without it, as Haskell correctly infers this type if you don't supply it.) - I changed the type of
boardArray
to useIO
. Anything that usesIO
, no matter how indirectly, need to be inIO
itself. - I changed
listArray (0, 100)
tolistArray (0, 99)
, as the former would actually be 101 elements. map randomBoard $ 100 (0,100)
isn't right at all. To get a list of several of the same thing, you'd usually usereplicate
, but since the thing you care about here is in theIO
monad, you usereplicateM
instead.replicateM 100 randomBoard
gives anIO [Char]
with 100 random elements of either'*'
or' '
.- I added an import of
Control.Monad
, which is needed to usereplicateM
. - I use
<$>
inboardArray
. Since you want to calllistArray
with a[Char]
and get anArray Int Char
, butreplicateM 100 randomBoard
is anIO [Char]
, you can't just apply the argument directly. Using<$>
(which is also calledfmap
) applies it "inside" ofIO
, giving you back anIO (Array Int Char)
.
这篇关于将函数映射到haskell中的列表/数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!