1

I am new to Haskell, and I am trying to write a function that replaces the first and the last element of a an array. When writing my code in GHCI, it works fine, but in VS Code it gives an error saying "parse error". My guess is that "let" works not the way that I assumed. Here is the function:

swap1 :: [x] -> [x]
swap1 [] = error "empty list"
swap1 [x] = error "one element list"
swap1 let a = head x
swap1 let b = last x
swap1 let y = init x
swap1 let z = tail y
swap1 = b:z ++ [a]
8
  • This doesn't work in ghci, it gives "parse error (possibly incorrect indentation or mismatched brackets)" on the first line using let.
    – cafce25
    Sep 18 at 4:50
  • By GHCI i meant if I run every line of code seperately
    – Delev1n
    Sep 18 at 5:00
  • Yes, that's the error you'll get because swap1 let a = head x is just nonesense.
    – cafce25
    Sep 18 at 5:02
  • I wrote it without swap1, because I do not declare a function in GHCI. And if it's nonsense, then please explain what is wrong.
    – Delev1n
    Sep 18 at 5:04
  • See that's why you don't modify code and make claims about the modified code that only apply to the unmodified one, see my answer for what's wrong. let a = head x (provided that x is defined) defines a new variable on ghci, which of course is not nonesense, swap1 let a = head x however is.
    – cafce25
    Sep 18 at 5:06

1 Answer 1

3

What you've written is mostly nonesense:

swap1 let a = head x

for example is missing the in <expr> part of let in (there is a special variant without in … but that's only valid with do blocks and as extension on the bare ghci command line), also x isn't defined anywhere in that clause and all previous definitions are either a type, which doesn't make sense here, or a single item, which doesn't make sense in combination with head either.

From your code I'm guessing you meant to write the following function:

swap1 [] = error "empty list"
swap1 [_] = error "one element list"
swap1 (a:y) = let b = last y
                  z = init y
               in b:z ++ [a]
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.