gpt4 book ai didi

haskell - 为什么这个函数隐含一个单曲面约束,即使只有 SemiGroup 被列为约束?

转载 作者:行者123 更新时间:2023-12-04 14:53:38 24 4
gpt4 key购买 nike

在以下堆栈脚本中,我无法应用我的 strangeHeadMay函数到 NonEmpty列表,但它在常规列表上工作正常。

#!/usr/bin/env stack
{- stack script --nix --resolver lts-13.6 -}

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# OPTIONS_GHC -Wno-partial-type-signatures #-} -- hide some scary types

import Control.Arrow ((&&&))
import Control.Monad (join)
import Data.Foldable (toList)
import Data.Function ((&))
import Data.Functor ((<&>))
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as LNE
import Data.Maybe (catMaybes)
import Data.Tuple.Sequence (sequenceT)


strangeHeadMay :: forall a t. (Semigroup (t a), _) => t a -> Maybe a
strangeHeadMay xs =
let xsWrapped :: t (t a) = pure <$> xs -- <- Contrived example
-- This is the functionality I actually need:
xsMay :: Maybe (t a) = xsWrapped & (headMay &&& tailMay) & sequenceT
<&> (\(h, t) -> foldr mappend h t)
in do
xs' <- xsMay
xs' & toList & headMay

main :: IO ()
main = do
let nexs :: NonEmpty (Maybe Double) = Nothing :| [Just (2.0)]
let xs = LNE.toList nexs
let xsHead = strangeHeadMay xs
let nexsHead = strangeHeadMay nexs
pure ()


headMay :: Foldable f => f a -> Maybe a
headMay = foldr (const . Just) Nothing

tailMay :: Foldable f => f a -> Maybe (f a)
tailMay = foldr (seq . Just) Nothing

错误是
/home/brandon/workspace/foldNEmaybes.hs:34:18: error:
• No instance for (Monoid (NonEmpty (Maybe Double)))
arising from a use of ‘strangeHeadMay’
• In the expression: strangeHeadMay nexs
In an equation for ‘nexsHead’: nexsHead = strangeHeadMay nexs
In the expression:
do let nexs :: NonEmpty (Maybe Double) = Nothing :| ...
let xs = LNE.toList nexs
let xsHead = strangeHeadMay xs
let nexsHead = strangeHeadMay nexs
....
|
34 | let nexsHead = strangeHeadMay nexs
| ^^^^^^^^^^^^^^^^^^^

另外,我必须承认我并不完全清楚为什么我需要部分键入的签名,而是更改 (Semigroup (t a), _)(Semigroup (t a))使坏事发生。

最佳答案

即使 <>mappend做同样的事情,如果你有 Monoid,你只能使用后者约束,所以一个被添加到你的 _在类型签名中。要修复它,请使用 foldr (<>)而不是 foldr mappend .

而且您不需要类型签名中的孔。你可以写出里面的内容,它仍然可以工作:Applicative tFoldable t .

关于haskell - 为什么这个函数隐含一个单曲面约束,即使只有 SemiGroup 被列为约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58963601/

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