是否可以使用括号语法糖作为应用函子? [英] Is it possible to use a bracketing syntactic sugar for an applicative functor?

查看:119
本文介绍了是否可以使用括号语法糖作为应用函子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

McBride和Paterson的'Applicative programming with effects'中,他们引入了一些可爱的语法糖来提升纯功能:

In McBride and Paterson's 'Applicative programming with effects' they introduce some lovely syntactic sugar for lifting a pure function:

[| f x y z |]

for

f <$> x <*> y <*> z

我记得有人在其他地方使用 li fwxyz il il fvwxyz li ,我想/可能是因为它可以使用一些现有的语言功能和 li的狡猾定义来定义和 il

and I recall someone somewhere else using li f w x y z il or il f v w x y z li, and I thought/hoped that might be because it could be defined using some existing language feature and cunning definition of li and il.

我无法在文章后面找到任何提及,假设 [| 和 |] 很快就不会在ghc中出现,是吗?有可能以某种方式实现 li il ?我想不出他们的明智类型,所以我认为我需要模板Haskell或类似的,但不知道完成这个。 [AF | fxy] 会很好,但我不知道在开始尝试之前是否有可能,并且确实需要帮助。

I can't find any reference to this beyond the paper, and assuming that [| and |] aren't likely to turn up in ghc any time soon, is it possible to implement li and il somehow? I can't think of a sensible type for them, so I assume I'd need Template Haskell or similar, but don't know nearly enough to accomplish this. [af| f x y ] would be fine, but I don't know whether it's possible before I start attempting it, and certainly need help if it is.

推荐答案

通过使用 haskell-src-meta 包在准引号中解析Haskell表达式。

This is pretty easy to implement in Template Haskell by using the haskell-src-meta package to parse the Haskell expression in the quasi-quotation.

{-# LANGUAGE TemplateHaskell #-}

import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Language.Haskell.Meta (parseExp)

import Control.Applicative ((<*>), (<$>))

af = QuasiQuoter
    { quoteExp  = parseAf
    , quotePat  = undefined
    , quoteType = undefined
    , quoteDec  = undefined
    }

parseAf :: String -> Q Exp
parseAf s = case parseExp s of
    Right ex -> applyExp ex
    Left err -> fail err

applyExp :: Exp -> Q Exp
applyExp (AppE f@(AppE _ _) a) = [|$(applyExp f) <*> $(return a)|]
applyExp (AppE f a) = [|$(return f) <$> $(return a)|]
applyExp _ = fail "invalid expression in af"

请注意,由于模板Haskell的工作原理,您不能在定义它的同一文件中使用quasiquoter,因此请将上述内容保存到它自己的模块中。

Note that due to how Template Haskell works, you can't use the quasiquoter from the same file where it's defined, so save the above to its own module.

测试GHCi

Testing in GHCi

*Main> :set -XTemplateHaskell
*Main> :set -XQuasiQuotes
*Main> [af|(+) (Just 3) (Just 8)|]
Just 11
*Main> [af|(+) (Just 6) Nothing|]
Nothing

这篇关于是否可以使用括号语法糖作为应用函子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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