haskell - Convert function into 1 liner
问题描述
After doing
>import Text.ParserCombinators.Parsec
and
>data Tag = MkTag String deriving Show
I have this function
parseDiv = do
string "<div>"
return (MkTag "div")
and I want to convert it into a 1 liner for ghci. I could have used :{ ... :} but want to understand why it didn't work. This is the 1 line
>let parseDiv = do { string "<div>";return $ MkTag "div" }
<interactive>:7:5: error:
* Non type-variable argument
in the constraint: Text.Parsec.Prim.Stream s m Char
(Use FlexibleContexts to permit this)
* When checking the inferred type
parseDiv :: forall s (m :: * -> *) u.
Text.Parsec.Prim.Stream s m Char =>
Text.Parsec.Prim.ParsecT s u m Tag
It works if I define it across multiple lines.
解决方案
You can define this with (<$) :: Functor f => a -> f b -> f a
. This thus performs a functor mapping with x <$ u = fmap (const x) u
:
{-# LANGUAGE FlexibleContexts #-}
parseDiv :: Stream s m Char => ParsecT s u m Tag
parseDiv = MkTag "div" <$ string "<div>"
推荐阅读
- apache-kafka - 卡夫卡连接错误:java.util.concurrent.ExecutionException:org.apache.kafka.connect.runtime.rest.errors.BadRequestException
- react-native - 简单的 React Native Button 不运行函数 onPress
- reactjs - 赛普拉斯错误“自动化客户端已断开连接。无法继续运行测试。” 在 Docker 中运行时
- c# - 为什么我需要构建我的 C# 项目(引用 F# 项目)两次才能正常工作?
- html - 当我将绝对位置应用于光滑箭头主图像时,ionic4 .in 滑块中的光滑滑块出现问题
- variables - 如何在不需要从控制器传递值的情况下制作存储过程变量?
- sql-server - 使用数据透视函数排序数据并选择辅助表上的特定列
- hive - 在 presto cli 中执行删除查询后,选择查询有什么问题吗?
- c++ - 当向量增长时,指向向量元素的 C++ 指针是否会变得无效?
- ubuntu - 无法在 ubuntu 18.04 中为 rvm 安装 libssl-dev