Search code examples
haskellfunctional-programming

Haskell: add multiple things to a list


I have an assigment and im kinda stuck:

xs = [4, 1]
ys = [3, 2]

the goal is to create a list [1, 2, 3, 4]

I am allowed to use the following commands: head, tail, ++, !!, reverse, take, drop, init

I know that tail xs ++ (reverse ys) results in [1, 2, 3]

but how do i get the 4 at the end?

My "solution" would have been something along the lines of:

zs = tail xs ++ (reverse ys +++ (head xs)
zs = [1, 2, 3, 4]

but instead im getting the following error:

<interactive>:39:1: error:
    * Non type-variable argument in the constraint: Num [a]
      (Use FlexibleContexts to permit this)
    * When checking the inferred type
        it :: forall a. (Num a, Num [a]) => [a]

The problem is i have no clue what that means It would be nice if someone could explain me how the brackets work in haskell and how i can solve the problem.


Solution

  • You have unbalanced parentheses in your demonstrated attempt.

    tail xs ++ (reverse ys +++ (head xs)
    

    Assuming you meant:

    tail xs ++ (reverse ys ++ (head xs))
    

    head xs is not a list, so using it with ++ will yield an error. But we can make it a list with a single element quite easily.

    tail xs ++ (reverse ys ++ [head xs])
    

    This now yields [1, 2, 3, 4], but you can further remove the parentheses because of how ++ associates.

    tail xs ++ reverse ys ++ [head xs]