New to Haskell, don't understand why I get an endless error like

module Main where

rev :: [a] -> [a]
rev (x:[]) = x
rev (x:xs) = (rev xs):x

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

main = do
   print (rev lst)

I make my way through 99 Haskell Problems and try to write a function to cancel the list (yes, I know that there is one already in foreplay).

My problem is that when I try to compile the above code (or just enter the function definition in GHCi), I get:

Occurs check: cannot construct the infinite type: a = [a]
In the expression: rev :: [a] -> [a]
In the definition of `it': it = rev :: [a] -> [a]

I am not quite sure where I am mistaken in my types to get this error. I guess this has something to do with how I map patterns, but I don't know why.

+5
source share
2 answers

The problem is that the type (:)is equal a -> [a] -> [a], but your third line ( rev (x:xs) = (rev xs):x) should be [a] -> a -> [a].

, , snoc (.. cons, (:) Lisp). Haskell, (++):

rev :: [a] -> [a]
rev (x:[]) = [x]
rev (x:xs) = rev xs ++ [x]

EDIT: , Landei : , , .

+9

, , " ", ( , ) :

, , , , - ​​ , . - . , - . .

, , , GHC . :

  • , " , ", , , , ,

  • , , , a , [a], , , , a [a] [[a]] [[[a]]]... ..

+17

All Articles