types - How to define a Haskell function with an argument of "newtype"? -


i've defined newtype called poly. poly list representation of polynomial (a list of num's), , i'm trying define function "chop" takes off excess 0's end of poly.

chop takes 1 poly argument, , returns poly. reason i'm getting following error message:

expected constraint, ‘poly a’ has kind ‘*’ in type signature ‘chop’: chop :: poly => -> a

newtype poly = p [a]  chop :: poly => -> chop l = if (last l) == 0 chop (init l) else l 

in haskell, => character in type signature denotes type restriction. used in conjunction haskell typeclasses in order abstract away implementation details functions can used @ high level of abstraction.

in example, poly a new type according type system, not typeclass, function chop intended operate on directly:

chop :: poly -> poly chop (p l) = if (last l) == 0 chop (p $ init l) else p l 

but wait, doesn't compile! restriction comes comparison 0: (last l) == 0. here we're implicitly saying want elements of our poly a comparable zero, or in other words a must instance of num a. after all, wouldn't able chop polynomial of type poly (maybe string). our revised type signature is:

chop :: num => poly -> poly chop (p l) = if (last l) == 0 chop (p $ init l) else p l 

one thing take consideration: because using newtype , not plain old type, haskell treating poly a new type. in order make interchangeable lists, can use type synonym:

type poly = [a] 

this simplify implementation of chop:

chop :: num => poly -> poly chop l = if (last l) == 0 chop (init l) else l 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -