What type should be given to a function that measures the data structure? Int, Integer, Integral?

I have a data structure such as an expression tree or graph. I want to add some "dimensional" functions, such as depthand size.

What is the best way to type these features?

I see the following three options of approximately equal utility:

  • depth :: Expr -> Int
  • depth :: Expr -> Integer
  • depth :: Num a => Expr -> a

I have the following considerations:

  • I am considering baseand fglhow examples, and they are consistently used Int, but Data.Listalso has the features like genericLengththat are polymorphic in reverse type, and I, I think, perhaps, the addition of these functions genericis a reflection of modernizing tendencies, which I probably should respect and strengthen.

  • A similar thought movement is noticeable in some widely used libraries that provide a complete set of functions with the same functionality when the user is offered several possible options for the return type (for example, it xml-conduitoffers parsers that take either lazy or strict forms either ByteString, or Text).

  • Integeris a nicer type than Int, and sometimes I find that I need to specify the length of the list in Integer, say, because the algorithm that works in Integershould consider this length.

  • The return of functions Integralmeans that these functions are made polymorphic and may have performance limitations. I don’t know all the details, but as I understand it, there may be some cost at runtime, and polymorphic things are harder to remember.

? , ? (I.e. Data.List , , , length?) - ?

+4
2

: , Int, , fromIntegral. ( , fi = fromIntegral, .)

- . , . Int , ( 30- , 32- GHC 32- ), , , Integer ( bignum, ). , . 5-10 , Int Integer s.

:

depth :: Expr -> Integer
depth :: (Num a) => Expr -> a

, Int, , . , , , Int , , .

:

-, generic* Data.List . , genericLength GHC 0.29, 1996 . length genericLength, :

length :: [a] -> Int
length = genericLength

GHC 0.29 #ifdef USE_REPORT_PRELUDE, length . generic* 0.29, GHC 4.02 (1998).

, Prelude length Foldable s, ( GHC 7.10?), , genericLength. , - , " " Haskell. .

-, lazy/strict ByteString/Text . , conduit-xml ByteString Text , . conduit-xml Text , ByteString s, , Text , . , depth Int , , , fromInteger . depth, .

-, , Integer " " , . , depth count , , , , .

-, , . GHC , memoization .

, , Data.List , Int s.

+6

K. A. Buhr , :

Integer, , - ( , ). Expr -> Integer, , , codomain .

Re. Integer: , . , :

data Integer = SmallInteger Int | LargeInteger ByteArray

. . , , , ( ), .

, Int ( Word) , , Int# -> Int# ->. Int# . , , , .

Re. : , , , . , . , (, , -XOverloadedStrings) , , base , , ( fromIntegral).

, , Word, , depth . , : Word - , ( GHC ); - , .

+3

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


All Articles