Haskell Esqueleto project to list of records instead of tuples

家住魔仙堡 提交于 2019-12-24 07:05:20

问题


In all the examples I have seen the results from esqueleto are projected into a list of tuples. This makes coding and maintenance harder because of lack of labels.

For example:

previousLogItems <- select $ from $ \li -> do
        orderBy [desc (li ^. LogItemId)]
        limit 10
        return (li ^. LogItemId, li ^. LogItemTitle)

Is there any way to get esqueleto to project the results to a list of records instead?


回答1:


In fact you construct the tuple yourself. Indeed:

previousLogItems <- select $ from $ \li -> do
        orderBy [desc (li ^. LogItemId)]
        limit 10
        return (li ^. LogItemId, li ^. LogItemTitle)

You thus make use of the (^.) :: (PersistEntity val, PersistField typ) => expr (Entity val) -> EntityField val typ -> expr (Value typ) "selector" to obtain the fields and wrap them into a tuple.

If you write it like:

previousLogItems >- select $ from $ \li -> do
        orderBy [desc (li ^. LogItemId)]
        limit 10
        return li

You will obtain a list of [Entity Foo] where Foo is the type of object you query.

You can use the entityVal :: Entity a -> a to obtain the entity that is wrapped into the Entity, for example:

previousLogItems <- select $ from $ \li -> do
        orderBy [desc (li ^. LogItemId)]
        limit 10
        return li
mapM_ (print . entityVal) previousLogItems

given the entity is of course an instance of Show.



来源:https://stackoverflow.com/questions/50143475/haskell-esqueleto-project-to-list-of-records-instead-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!