Why is this form acceptable, but another form causes a type error?

While working through Real World Haskell, I tried to perform a palindrome exercise using the following code solution:

palin :: [a] -> [a]
palin list = list ++ rev list
    where rev list
           | null list = []
           | otherwise = rev (tail list) ++ (head list)

What caused "cannot build an error of infinite type. However, just replacing the parenthesis around the title with square brackets and it works correctly, as shown in the following example:

palin :: [a] -> [a]
palin list = list ++ rev list
    where rev list
           | null list = []
           | otherwise = rev (tail list) ++ [head list]

I really do not understand why this matters, and I do not understand what it means "cannot build an infinite type a = [a]". Can someone explain this?

+3
source share
3 answers

. head list , a. ++ , -, . [head list], 1 . [] .

+10

, , :

(tail list) ++ (head list)

, `list - -. , :

list::[a]

:

(tail list)::[a]

:

(head list)::a

`++, , . ,

a == [a] 

:

a == [a] == [[a]] == [[[a]]] ...etc.

.

+10

++has type [a] -> [a] -> [a], i.e. it takes two lists of a certain type and creates another list of the same type. The OTOH function headhas a type [a] -> a, i.e. Accepts a list of some type and returns a value of that type. In your first example, I ++got it [a]in my left hand and ain my right hand. Trying to combine these types of type checking creates this error. In the second example, you built a singleton list from the result headand it has a type [a], so type checking is happy.

+7
source

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


All Articles