haskell

The same function works when using GHCI, but not in VS code


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]

Solution

  • 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]