将函数应用于列表并将其结果传递给构造函数?
如何编写 flipv
一次,将其应用于列表 [se, sq, nw, ne]
的每个元素,并将结果(当然不是列表)提供给Q
构造函数?
data (Eq a, Show a) => QT a = C a | Q (QT a) (QT a) (QT a) (QT a)
deriving (Eq, Show)
flipv :: (Eq a, Show a) => QT a -> QT a
flipv (C a) = C a
flipv (Q nw ne se sw) = Q (flipv se) (flipv sw) (flipv nw) (flipv ne)
编辑:请注意这实际上是错误的,因为指针应该是:NW NE SW SE。
How can just write flipv
one time applying it to each element of list [se, sq, nw, ne]
, giving the result (not as a list of course) to the Q
constructor?
data (Eq a, Show a) => QT a = C a | Q (QT a) (QT a) (QT a) (QT a)
deriving (Eq, Show)
flipv :: (Eq a, Show a) => QT a -> QT a
flipv (C a) = C a
flipv (Q nw ne se sw) = Q (flipv se) (flipv sw) (flipv nw) (flipv ne)
EDIT: note this actually wrong because the pointers should be: NW NE SW SE.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有特别简单或紧凑的方法,但您可以尝试以下方法:
There is no particularly simple or compact method, but you could try this:
如果不枚举所有四个参数,基本上没有简单的方法可以做到这一点,因为否则,如何确保列表具有正确数量 (4) 的元素?
There's basically no simple way to do it without enumerating all four arguments, because otherwise, how can you make sure that the list has the right number (4) of elements?
乍一看,我打算建议
toList
和fromList
。虽然代码较多,但最终可以实现优雅的组合。在 ghci 中进行松散测试
现在,您也可以轻松地在 QT 结构上进行“排序”。
作为之前 ghci 会话的一部分进行了测试...
请注意,对翻转的 q 和简单的 q 进行排序都得到相同的结果(因此排序可能有效!耶)。您可能想要选择一个更好的
compare
实现,我只是将其放在一起看看会发生什么。那么它是如何工作的?
正如您可能已经猜到的那样,它的神奇之处在于
listOpOnQT
。在重要的情况下,它将 QT 结构转换为列表,将 listy 函数应用于列表,将 lifted listy 函数映射到列表的所有元素,然后将列表拉回QT 结构。listOpOnQT
的更好名称可能是liftQT
,尽管它只适用于非常特殊的函数......At first glance, I was going to suggest
toList
andfromList
. It's more code, but it enables elegant composition in the end.Loosely tested in ghci
You can easily make 'sort' work on your QT structure as well, now.
Tested as part of the previous ghci session...
Notice sorting the flipped q and just plain q both came out with the same result (therefore the sorting probably works! yay). You might want to pick a better implementation of
compare
, I just threw that one together to see stuff happen.So how does it work?
The magic sauce, as you might have guessed, is
listOpOnQT
. In the non-trivial case, it turns the QT structure into a list, applies the listy function to the list, maps the lifted listy function on all elements of the list, and then pulls the list back into a QT structure. A better name forlistOpOnQT
might beliftQT
, though it only works for a very special kind of function...获取一个列表并抛出一个 QT。
takes a list and throws a QT.