# [Haskell-cafe] Determining the length of a Foldable Applicative.

David Feuer david.feuer at gmail.com
Fri Oct 30 21:42:56 UTC 2015

```You don't need the Applicative context. In fact, in the latest version
of the library, length is a member of the Foldable class, but even for
older versions, you can define

length :: Foldable f => f a -> Int

Does limiting yourself that way help guide you to a correct solution?

On Fri, Oct 30, 2015 at 4:03 PM, David Banas <capn.freako at gmail.com> wrote:
> Hi all,
>
> I thought I had a simple way to determine the “length" (i.e. - number of elements in) of a Foldable Applicative container:
>
>     import Prelude hiding (sum)
>     import Data.Foldable (Foldable(..), sum)
>     import Control.Applicative
>
>     -- Calculate the "length" (i.e. - number of elements in) an Applicative container.
>     app_len :: (Applicative f, Foldable f) => f a -> Int
>     app_len = sum \$ pure 1
>
> but I didn’t:
>
> app_len_test.hs:9:11:
>     Could not deduce (Foldable t0) arising from a use of ‘sum’
>     from the context (Applicative f, Foldable f)
>       bound by the type signature for
>                  app_len :: (Applicative f, Foldable f) => f a -> Int
>       at app_len_test.hs:8:12-52
>     The type variable ‘t0’ is ambiguous
>     Note: there are several potential instances:
>       instance Foldable ((,) a) -- Defined in ‘Data.Foldable’
>       instance GHC.Arr.Ix i => Foldable (GHC.Arr.Array i)
>         -- Defined in ‘Data.Foldable’
>       instance Foldable (Const m) -- Defined in ‘Data.Foldable’
>       ...plus four others
>     In the expression: sum
>     In the expression: sum \$ pure 1
>     In an equation for ‘app_len’: app_len = sum \$ pure 1
>
> app_len_test.hs:9:17:
>     Could not deduce (Applicative t0) arising from a use of ‘pure’
>     from the context (Applicative f, Foldable f)
>       bound by the type signature for
>                  app_len :: (Applicative f, Foldable f) => f a -> Int
>       at app_len_test.hs:8:12-52
>     The type variable ‘t0’ is ambiguous
>     Note: there are several potential instances:
>       instance Data.Monoid.Monoid a => Applicative ((,) a)
>         -- Defined in ‘Control.Applicative’
>       instance Applicative ((->) a) -- Defined in ‘Control.Applicative’
>       instance Control.Arrow.Arrow a =>
>         -- Defined in ‘Control.Applicative’
>       ...plus 14 others
>     In the second argument of ‘(\$)’, namely ‘pure 1’
>     In the expression: sum \$ pure 1
>     In an equation for ‘app_len’: app_len = sum \$ pure 1
>
> Can anyone help me understand what I’m missing?
>
> Thanks, and have a great weekend,
> -db
>
> _______________________________________________