简体   繁体   English

输入IO的haskell说明

[英]Type in haskell explanation of IO

Can any one help me with understanding this function type? 有人可以帮助我了解此功能类型吗? stateOfMind :: BotBrain -> IO (Phrase -> Phrase)

stateOfMind is a function and BotBrain is just a type. stateOfMind是一个函数, BotBrain只是一个类型。

type Phrase = [String]
type PhrasePair = (Phrase, Phrase)
type BotBrain = [(Phrase, [Phrase])]

If stateOfMind had this type: BotBrain -> (Phrase -> Phrase) , then stateOfMind would take a BotBrain as an argument to produce a new function that takes a Phrase and gives a Phrase as a result. 如果stateOfMind具有以下类型: BotBrain -> (Phrase -> Phrase) ,则stateOfMindBotBrain作为参数来产生一个新函数,该函数接受一个Phrase并给出一个Phrase But now we have an IO , ie IO (Phrase -> Phrase) . 但是现在我们有了一个IO ,即IO (Phrase -> Phrase) What does that mean? 这意味着什么?

randomIO has monadic type but why is to like that? randomIO具有单子类型,但为什么要那样呢? Is is because of the seed we choose? 是因为我们选择了种子吗? Monadic I normally used for input and output, but a random generator actually doesn't get any input from user at run time. Monadic我通常用于输入和输出,但是随机生成器实际上在运行时没有从用户那里获得任何输入。

stateOfMind :: BotBrain -> IO (Phrase -> Phrase)

stateOfMind takes a BotBrain and returns an IO action whose result is a function from Phrase to Phrase . stateOfMind接受BotBrain并返回IO操作,其结果是从PhrasePhrase的函数。 When you execute an IO (Phrase -> Phrase) action in the IO monad, you get an ordinary pure function Phrase -> Phrase . IO monad中执行IO (Phrase -> Phrase)操作时,将获得普通的纯函数Phrase -> Phrase

randomIO is in IO because it uses getStdRandom to change the state of the global standard random number generator. randomIO属于IO因为它使用getStdRandom更改全局标准随机数生成器的状态。 Multiple calls to randomIO can (and will) return different results, which is precisely what IO indicates. 多次调用randomIO可以(并且将)返回不同的结果,这正是IO指示的。

You can create a pure generator with mkStdGen and get values from it purely: 您可以使用mkStdGen创建一个纯生成器,并从中纯粹获取值:

let
  g1 = mkStdGen 42      -- Seed value
  (r1, g2) = random g1  -- Get first random number
  (r2, g3) = random g2  -- Get second random number
in r1 + r2

And a convenient way to get rid of the repetition here is to use the State monad: 摆脱重复的一种方便方法是使用State monad:

flip evalState (mkStdGen 42) $ do
  r1 <- state random
  r2 <- state random
  return (r1 + r2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM