编写自定义地图功能 [英] Writing a custom map function

查看:122
本文介绍了编写自定义地图功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在Haskell库中可能会有些东西可以做我想做的事情。我已经足够了,不知道什么更好,我正在尝试使用我知道的工具编写自定义地图函数。类型签名需要是

  myMap ::(Monad m)=> (a  - > b) - > [m a]  - > [mb] 

其中 myMap f 返回将 f 应用于中每个Monad中每个值的列表。



我的第一次尝试是

  myMap f = map(\xx>> = f) 

然而,这有一个类型签名

  myMap ::(Monad m)=> (a  - > m b) - > [m a]  - > [m b] 

这与我所需要的非常接近,我可以尖叫。现在我需要一些关于如何从这里继续的提示。我真的希望它像库函数一样简单,但我愿意编写自己的短函数来完成这个任务。



相关问题:



将函数映射到两个输入列表

解决方案

如果您可以将您的(a - > b)函数到 ma - > m b 那么你可以使用 map 本身。那么,你需要做什么? Hoogle对这类事情非常好。搜寻(a - &b; b) - > (ma - > mb)会给出以下结果:

http://www.haskell.org/hoogle/?hoogle=%28a+-% 3E + b%29 + - %3E +%28m + a + - %3E + m + b%29 $ b

> fmap (它使用 Functor )和 liftM (它使用单子)。要么可以,但是你使用单子,所以让我们一起去 liftM 。因此:

  myMap :: Monad m => (a  - > b) - > [m a]  - > [m b] 
myMap f = map(liftM f)


Now there might be something in the Haskell Libraries to do what I want. I'm enough of a noob to not know any better and I'm trying to write a custom map function using the tools that I know. The type signature needs to be

myMap :: (Monad m) => (a -> b) -> [m a] -> [m b]

where myMap f as returns a list after applying f to each of the value in each Monad in as.

My first attempt was

myMap f = map (\x x >>= f)

However, this has a type signature of

myMap :: (Monad m) => (a -> m b) -> [m a] -> [m b]

This is so close to what I need, I can scream. Now I need some tips of how to continue from here. I really hope it is as easy as a library function, but I'm willing to write my own short function to do this instead.

Related Question:

Mapping a function over two input lists

解决方案

If you could turn your (a -> b) function in to m a -> m b then you could use map itself. So, what do you need to do this? Hoogle is quite good for this sort of thing. Doing a search for (a -> b) -> (m a -> m b) gives these results:

http://www.haskell.org/hoogle/?hoogle=%28a+-%3E+b%29+-%3E+%28m+a+-%3E+m+b%29

Near the top are fmap (which use Functor) and liftM (which use Monad). Either would do, but you're using monads, so let's go with liftM. Thus:

myMap :: Monad m => (a -> b) -> [m a] -> [m b]
myMap f = map (liftM f)

这篇关于编写自定义地图功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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