purescript

PureScript - Splitting Array of Positive and Negative Numbers into Tuple of 2 Arrays of Positive and Negative Numbers


I'm a newbie in PureScript now reading a book "Functional Programming Made Easier: A Step-by-Step Guide", but when I got to the section on Tuples, I realised that all that was presented appeared to be nonsense.

This is the code that's presented that does not work.

splitPosAndNeg :: Array Int -> Tuple (Array Int) (Array Int)
let Tuple pos neg = splitPosAndNeg [1, -2, 3, -4, 5, -6, -7, 8]
let split = splitPosAndNeg [1, -2, 3, -4, 5, -6, -7, 8]
  pos = fst split
  neg = snd split

Could someone explain how to split an Array of Positive and Negative Numbers into a Tuple of 2 Arrays of Positive and Negative Numbers using PureScript? Would partition from Data.Array work? How is it used?

@Fyodor Soikin, I've tried out the book's code here with the partition function. It still does not work.


Solution

  • I don't have the book, so it's very hard to say where the disconnect is.

    But from snippet you posted, it kind of looks like the author is merely asserting that such function exists in the scope, without giving its implementation, because it's not important for the context. And to clarify what the function does, the author gives its type signature.

    splitPosAndNeg :: Array Int -> Tuple (Array Int) (Array Int)
    

    And then the author shows two examples of how the result of such function might be used. First example - by pattern-matching on the Tuple constructor:

    let Tuple pos neg = splitPosAndNeg [1, -2, 3, -4, 5, -6, -7, 8]
    

    And second example - by using fst and snd functions to obtain the first and second elements of the tuple respectively:

    let split = splitPosAndNeg [1, -2, 3, -4, 5, -6, -7, 8]
        pos = fst split
        neg = snd split
    

    (note that you probably have screwed up indentation in your snippet: pos and neg should be aligned under split)


    In response to your comment:

    Thanks, but the code still does not work. Please refer to my link in my updated post about my problem above. The link is too long to paste in a comment box.

    A let binding cannot be at top level, it has to be in a function body. Plus, the function implementation you added has the wrong type. Here, I fixed it for you.