Haskell List Return Error

I am writing a list spread program for haskell.

I have an idea for expanding the list, and this led to the following code:

myreverse list1
 | list1 == []    = list1
 | otherwise      = (myreverse(tail list1)):(head list1)

Unfortunately, the above code leads to the following error:

Occurs check: cannot construct the infinite type: a = [[a]]
 Expected type: [[a]]
 Inferred type: a
 In the second argument of '(:)', namely '(head list1)'
 In the expression: (myreverse(tail list1)):(head list1)

PS: I get the same error when I run it on the fragment that I wrote under the name mylast, encoded below:

mylast list
 | list == []      = []
 | otherwise       = mylast_helper(head list1)(tail list1)

mylast_helper item list2
 | list2 == []     = item
 | otherwise       = mylast_helper(head list2)(tail list2)

The error is in the otherwise recursive helper.

EDIT: Thanks for all the input, I probably forgot to mention that the limitations of the question forbid the use of the ++ operator. I will keep this in mind for future issues that I create.

Cheers, -Zigu

+1
source share
4 answers

You are using the function

(:) :: a -> [a] -> [a]

with incorrectly typed arguments:

myReverse (tail list1) :: [a]
head list1 :: a

list1 a. , , head list1, [a]. GHC , , . , , [a], a.

, , list1 myreverse, (++):

myReverse xs = case (null xs) of
               True  -> xs
               False -> myReverse (tail xs) ++ [head xs]

[head xs] :: [a]
myReverse (tail xs) :: [a]

:

(++) :: [a] -> [a] -> [a]

. ( myReverse:

reverse xs = foldr (\x xs -> xs ++ [x]) [] xs
+4

cons (:) - a -> [a] -> [a] - , , , . , - . , : concat ++:

myreverse list1
  | list1 == [] = list1
  | otherwise   = (myreverse (tail list1)) ++ [head list1]

( , : "OK, :, , - , , ... ... , , - , , , " t do. Bang! ")

+3

, ; , , . : mylast :: [a] -> a. (|) , :

mylast :: [a] -> a
mylast (x:[]) = x
mylast (_:t) = mylast t

GHCi -, :t. , ... , , .

+3

. . .

myreverse list1
 | list1 == []  = list1
 | otherwise    = myreverse_h(list1)([])

myreverse_h list1 list2
 | list1 == []  = list2
 | otherwise    = myreverse_h(tail list1)((head list1):list2)

Any comments on the best code? I do not consider it as effective as possible ...

+1
source

All Articles