点免费monadic表达

Eva*_*ian 3 haskell

考虑这个表达式(取自Real World Haskell第8章,我试图简化)

isElfFile :: FilePath -> IO Bool
isElfFile path = return . hasElfMagic =<< L.readFile path
Run Code Online (Sandbox Code Playgroud)

如何制作此功能的无点版本?我尝试使用其他绑定操作>>=,解除hasElfMagic,但似乎没有工作.

And*_*ács 8

没有绑定在这里更简单:

isElfFile path = return . hasElfMagic =<< L.readFile path
isElfFile path = fmap hasElfMagic (L.readFile path)
isElfFile      = fmap hasElfMagic . L.readFile 
Run Code Online (Sandbox Code Playgroud)

但当然也可以=<<:

isElfFile path = return . hasElfMagic =<< L.readFile path
isElfFile path = (=<<) (return . hasElfMagic) (L.readFile path)
isElfFile      = (=<<) (return . hasElfMagic) . L.readFile
isElfFile      = (return . hasElfMagic =<<) . L.readFile
Run Code Online (Sandbox Code Playgroud)

通常,在尝试使点无效之前,将中缀函数转换为前缀形式是有帮助的.

  • 还有`f <= <g =(f = <<).g`,对于你不能只使用`fmap`的情况. (3认同)
  • 好推荐.你可以回来.hasElfMagic <= <L.readFile`或者如果你愿意,`L.readFile> => return.haseElfMagic`.来自Control.Monad的方便的`> =>`用类似`a - > mb`的类型组成monadic函数.从某种意义上说,这是一种更好的思考monad的方法,因为如果你定义`> =>`和`return`而不是`>> =`和`return`,那么monad定律变得更容易理解. > => return = f`,`return> => f = f`,和`f> =>(g> => h)=(f> => g)> => h`. (3认同)