gpt4 book ai didi

haskell - 用于转换为有界积分的 Prism

转载 作者:行者123 更新时间:2023-12-02 16:13:11 24 4
gpt4 key购买 nike

我需要一个 Prism 将 Integral a => a 转换为 (Integral b, Bounded b) => b,确保 a 实际上适合 b 的类型。我当前的定义(如下)需要使用 ScopedTypeVariables 并且非常冗长。

我想知道是否有更好的(理想情况下已经定义了,但我错过了)方法来检查数字是否适合Bounded类型,或者安全的函数 转换,我可以用它来构建棱镜。

当前定义:

boundedInt :: forall a b. (Integral a, Integral b, Bounded b) => Prism' a b
boundedInt = prism fromIntegral f where
f n =
if n >= fromIntegral (minBound :: b) && n <= fromIntegral (maxBound :: b)
then Right (fromIntegral n)
else Left n

最佳答案

一个不太令人满意的答案:我认为没有一个库可以帮助您。

真的,你需要类似的东西

safeIntegerToBoundedIntegral :: (Integral b, Bounded b) => Integer -> Maybe b
safeIntegerToBoundedIntegral = boundedFromInteger (minBound, maxBound)

-- helper function's signature lets you avoid `ScopedTypeVariables`
boundedFromInteger :: Integral b => (b,b) -> Integer -> Maybe b
boundedFromInteger (lo,hi) n | toInteger lo <= n && n <= toInteger hi = Just (fromInteger n)
boundedFromInteger _ _ = Nothing

我目前在 hoogle 或 hayoo 上没有看到,那么你可以更轻松地表达它:

integerAsIntegral :: Integral a => Iso' Integer a
integerAsIntegral = iso fromInteger toInteger

integerAsBoundedIntegral :: (Integral a, Bounded a) => Prism' Integer a
integerAsBoundedIntegral = prism toInteger $ \n ->
maybe (Left n) Right $ safeIntegerToBoundedIntegral n

integralAsBoundedIntegral :: (Integral a, Integral b, Bounded b) => Prism' a b
integralAsBoundedIntegral = from integerAsIntegral . integerAsBoundedIntegral

我按照我所做的方式将其分开,因为我不知道 fromIntegral 有任何保证是保序的;也就是说,a < bfromIntegral a < fromIntegral b ,所以我决定使用 Integer作为规范顺序比较 Integral 时所以它至少是一致的。

关于haskell - 用于转换为有界积分的 Prism,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34201600/

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