是否有标准的Haskell函数(返回a)>> = b? [英] Is there a standard Haskell function for (return a) >>= b?

查看:91
本文介绍了是否有标准的Haskell函数(返回a)>> = b?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法从以下函数中移除 return s:

I'm looking for a way to remove the returns from the following function:

  naming path = 
    getModificationTime path                       >>=
    return . formatTime defaultTimeLocale "%Y%m%d" >>=
    return . printf "%s_%s" (takeBaseName path)    >>=
    return . replaceBaseName path

我这样构造它的原因是因为>> ; = 本质上变成了一种管道操作符,数据从一行流向另一行。

The reason why I structure it this way is because >>= essentially becomes kind of a pipe operator and data flows from one line to the next.

我想我可以定义一个操作符

I figured I can define an operator along the lines of

  a |>= b = (return a) >>= b

并获得

and get

  naming path = 
    getModificationTime path              >>=
    formatTime defaultTimeLocale "%Y%m%d" |>=
    printf "%s_%s" (takeBaseName path)    |>=
    replaceBaseName path

但是我收到错误

but I get the error

Precedence parsing error
    cannot mix `|>=' [infixl 9] and `.' [infixr 9] in the same infix expression

解决此问题的最佳方法是什么?更好的是,是否有某种标准运算符或其他方式可以更容易地以这种方式构造代码?

What's the best way to resolve this issue? Better yet, is there some sort of standard operator or other way to make it easier to structure the code this way?

推荐答案

推测你希望它的行为与>> = 具有相同的固定性,所以如果你加载GHCi并键入

Presumably you want it to behave with the same fixity as >>=, so if you load up GHCi and type

> :info (>>=)
...
infixl 1 >>=

然后你可以定义你的操作符为:b
$ b

You could then define your operator as

infixl 1 |>=
(|>=) :: Monad m => a -> (a -> m b) -> m b
a |>= b = return a >>= b

如果你的monad保留monad法则,这与仅仅做 ba 是一样的,所以对于操作员来说并不是真的需要它。

But, if your monad preserves the monad laws, this is identical to just doing b a, so there isn't really a need for the operator in the first place.

我还建议使用符号:

I'd also suggest using do notation:

naming path = do
    modTime <- getModificationTime path
    let str = formatTime defaultTimeLocale "%Y%m%d" modTime
        name = printf "%s_%s" (takeBaseName path) str
    replaceBaseName path name

这篇关于是否有标准的Haskell函数(返回a)&gt;&gt; = b?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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