Why is Haskell [] (list) not a type class?

I am writing a Haskell function that takes a list as input. That is, there is no reason why this could not be a queue or deactivation, or anything that allows me to access her "head" and "tail" (and check if it is empty). So the input type [a] seems too specific. But AFAIK there is no standard library type that captures this particular interface. Of course, I could wrap my function in Data.Foldable.toList and make it polymorphic wrt Foldable, but this is not entirely correct (idiomatic).

Why is there no standard list type class? (And why is the class hierarchy of the container type in Haskell less developed than I think it should be?) Or am I missing something substantial?

+4
source share
2 answers

This algebraic data type can be represented as its catamorphism, a transformation known as Church coding . This means that lists are isomorphic to them foldr:

type List a = forall b. (a -> b -> b) -> b -> b

fromList :: [a] -> List a
fromList xs = \f z -> foldr f z xs

toList :: List a -> [a]
toList l = l (:) []

But foldralso characterizes Foldable. You can define foldMapin terms foldrand vice versa.

foldMap f = foldr (mappend . f) mempty
foldr f z t = appEndo (foldMap (Endo . f) t) z

(No wonder what foldMap :: Monoid m => (a -> m) -> [a] -> mcharacterizes lists, because lists are a free monoid.) In other words, Foldablebasically gives you toListas a class. Instances Foldablehave a "path" that you can go through to give you a list; Foldablehave at least such a structure as lists.


Regarding your concerns:

, Foldable head/tail/isEmpty, .

null :: Foldable t => t a -> Bool isEmpty, ( ) head Monoid:

head :: Foldable t :: t a -> Maybe a
head = getFirst . foldMap (First . Just)

tail, , . , tail . , , tail :: Foldable t => t a -> Maybe [a] ( toList ing, ), , T, tail :: T a -> Maybe (T a), (, Seq). , , , , tail, .

, . megaparsec, , Stream () , .

+12

, :

class HasHeadAndTail t where
    head :: t a -> Maybe a
    tail :: t a -> Maybe (t a)
    isEmpty :: t a -> Bool

base?

. Map, Set, HashMap, HashTable Tree . Seq DList, "" .

, ? , if isEmpty False, head tail Nothing. isEmpty isEmpty :: HashHeadAndTail t => t a -> Bool ; isEmpty = isNothing . head.

, :

  • , .
  • , , .
+5

Source: https://habr.com/ru/post/1017145/


All Articles