haskell - purescript 中的应用函子和记录
问题描述
在 Haskell 中,我习惯于做这样的事情。
data Foo = Foo { foo :: String, bar :: String }
mFoo :: (Monad m) => m String -> m String -> m Foo
mFoo foo bar = Foo <$> foo <*> bar
但是,这在 purescript 中不起作用。有没有办法实现相同的结果,即在构建实例时保留记录语法,同时允许通过应用函子进行部分应用?
谢谢!
解决方案
在 PureScript 中,您不必预先定义这样的记录类型。多态版本:
mXY :: forall a b m. Apply m => m a -> m b -> m { x :: a, y :: b }
mXY foo bar = { x: _, y: _ } <$> foo <*> bar
-- | which can be rewritten using lift2:
mXY' = Control.Apply.lift2 { x: _, y: _ }
和一个等价的:
type Foo = { x :: String, y :: String }
mFoo :: forall m. Apply m => m String -> m String -> m Foo
mFoo = Control.Apply.lift2 {x: _, y: _ }
使用精彩的 try.purescript.org + 自定义要点的“现场演示”:
https://try.purescript.org/?gist=a37f5f0c50e0640e34ea5a4788c0c999
当然,使用newtype
around Record
too like 也有实用价值:
newtype Foo' = Foo' { x :: String, y :: String }
在这种情况下,我会提出类似的建议:
mFoo'' foo bar = map Foo' $ { x: _ , y: _ } <$> foo <*> bar
但我认为这可以用我不知道的更优雅和更短的方式来表达:-)
编辑:
这可能是更好的语法使用ado
:
mFoo''' foo bar = Foo' <$> ado
x <- foo
y <- bar
in
{ x, y }
推荐阅读
- vb.net - 将整数加一
- amazon-web-services - ClientError:调用 AssumeRole 操作时发生错误(AccessDenied):MultiFactorAuthentication failed with invalid MFA one time pass code
- c# - 目录右键
- sql - PostgreSQL 使用来自不同表列的自动计算列创建表
- asp.net-core-mvc - 找不到方法:'无效 EntityFrameworkCore.Design.Internal.DbContextOperations
- c# - C#在分配之前设置字符串长度并在剩余位置添加空格
- javascript - Vue.js 访问组件方法还是父方法?
- python - Python:具有多个标题的 CSV 文件 - 组合成一个数据框?
- powerbi - 在子项目类别 powerbi 上过滤项目
- c++ - 非递归后序图遍历?