gpt4 book ai didi

haskell - 如何抽象 "back and forth"转换?

转载 作者:行者123 更新时间:2023-12-03 15:04:47 28 4
gpt4 key购买 nike

考虑这个例子(来自 https://codereview.stackexchange.com/questions/23456/crtitique-my-haskell-function-capitalize ):

import Data.Char

capWord [] = []
capWord (h:t) = toUpper h : map toLower t

capitalize = unwords . map capWord . words

有没有一种很好的方法来抽象“来回”转换,例如 unwords . f . words ?我能想到的最好的是
class Lift a b | a -> b where
up :: a -> b
down :: b -> a

instance Lift String [String] where
up = words
down = unwords

lifted :: (Lift a b) => (b -> b) -> a -> a
lifted f = down . f . up

capitalize = lifted (map capWord)

但感觉不是很灵活,需要 MultiParamTypeClassesFunctionalDependenciesTypeSynonymInstancesFlexibleInstances ——这可能表明它稍微超出了顶部。

最佳答案

您的 lifted实际上与 dimap 相同来自 Data.Profunctor :

onWords = dimap words unwords
capitalize = onWords (map capWord)

这可能不是您考虑的泛化方向。但是看看 Control.Functor 中等价函数的类型来自 category-extras :
dimap :: Bifunctor f (Dual k) k k => k b a -> k c d -> k (f a c) (f b d)

这个版本将它概括为所有 QFunctor和一个合作- PFunctor .在日常场景中不是那么有用,但很有趣。

关于haskell - 如何抽象 "back and forth"转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15222013/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com