将Haskell IO列表转换为列表类型 [英] Convert Haskell IO list to list type

查看:111
本文介绍了将Haskell IO列表转换为列表类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

haskell-problem:io string - >如何将Haskell IO列表转换为普通列表? / p>

  IO [value]  - > [b] 

有没有内置函数可以做到这一点?

有些方法可以做你要求的,但它是不安全的。因此,我认为你应该反过来看待这个问题。在从 IO 列表中取出列表时,应该将纯函数放到 IO 中。



假设您想从数据库中获取列表并应用一些纯函数,那么您可以执行以下操作:

  yourFunc = do 
list< - getListFromDB
return(myPureFunction List)

,或者如果你想打印结果的话:

  yourFunc = do 
list <-getListFromDB
print(myPureFunction List)

通常,为了计算在您可以使用的IO monad中输入纯
结果:

  yourFunc = do 
list< ; - getListFromDB
let result = myPureFunction list
返回结果

或更紧凑:

  import Control.Monad((= <?lt))
import Control.Applicative((< $>))

yourFunc = print =<< myPureFunction< $> getListFromDB


Possible Duplicate:
haskell-problem: io string -> [int]

How I can convert Haskell IO list to normal list?

IO [value] -> [value]

Is there any built in function to do this?

解决方案

There are ways of doing what you ask for, but it is unsafe. Therefore, I think you should be looking at the problem the other way around. In staid of getting the list out of IO, you should lift your pure function into IO.

Let's say you wanted to get the list from DB and apply some pure function to it, then you could do the following:

yourFunc = do
  list <- getListFromDB
  return (myPureFunction List)

or if you want to print the result afterwords:

yourFunc = do
  list <- getListFromDB
  print (myPureFunction List)

In general, in order to calculate a pure result inside of the IO monad you can use let:

yourFunc = do
  list <- getListFromDB
  let result = myPureFunction list
  return result

or more compact:

import Control.Monad((=<<))
import Control.Applicative((<$>))

yourFunc = print =<< myPureFunction <$> getListFromDB

这篇关于将Haskell IO列表转换为列表类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆