gpt4 book ai didi

haskell - 更高等级和含蓄的类型

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

我想实现以下 stripPrefixBy功能:

-- psuedo code signature
stripPrefixBy :: forall a. [forall b. a -> Maybe b] -> [a] -> Maybe [a]
stripPrefixBy [] xs = Just xs
stripPrefixBy _ [] = Nothing
stripPrefixBy (p:ps) (x:xs) = case p x of
Just _ -> stripPrefixBy ps xs
Nothing -> Nothing

res :: Maybe String
res = stripPrefixBy [const (Just 0), Just] "abc"

wantThisToBeTrue :: Bool
wantThisToBeTrue = case res of
Just "c" -> True
_ -> False

我试过使用 ImpredicativeTypesRankNTypes但没有运气。如何实现 stripPrefixBy与我想要的类型?

最佳答案

您签名的问题是列表传递给 stripPrefixBy被声明为以某个 a 作为参数的函数列表,然后生成 Maybe b对于调用者选择的任何 b。列表中的函数允许返回的唯一值是 , NothingJust ⊥ .

也就是说,当使用含意多态性时,forall与存在量化类型的含义不同:在那里,forall应用于构造函数的类型,即

data MyType = forall a. Foo a
Foo :: forall a. a -> MyType

但在这里,它的意思是函数必须是 forall b. a -> Maybe b 类型。 .

这是一个使用存在类型的更正示例:
{-# LANGUAGE ExistentialQuantification #-}

data Pred a = forall b. Pred (a -> Maybe b)

stripPrefixBy :: [Pred a] -> [a] -> Maybe [a]
stripPrefixBy [] xs = Just xs
stripPrefixBy _ [] = Nothing
stripPrefixBy (Pred p:ps) (x:xs) = case p x of
Just _ -> stripPrefixBy ps xs
Nothing -> Nothing

res :: Maybe String
res = stripPrefixBy [Pred $ const (Just 0), Pred Just] "abc"

wantThisToBeTrue :: Bool
wantThisToBeTrue = case res of
Just "c" -> True
_ -> False

我相信 UHC支持直接表达你想要的类型,如
stripPrefixBy :: [exists b. a -> Maybe b] -> [a] -> Maybe [a]

关于haskell - 更高等级和含蓄的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8739741/

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