Trying to use Cons function in Purescript - purescript

Heres my code:
print 1: [2,3]
When I run it I get
Cannot unify type
Data.List.List
with type
Prim.Array
Whats going on?

[2, 3] has type Array Int. (:) has type a -> List a -> List a in Data.List. You need to convert to a List. Also, what you have will parse as
(print 1) : [2, 3]
I think you want
print (1 : toList [2, 3])
or
print $ 1 : toList [2, 3]

In psci, look at the type of (:)
> :t (:)
forall a. a -> Data.List.List a -> Data.List.List a
and the type of [2, 3]
> :t [2, 3]
Prim.Array Prim.Int
You can see that the (:) function expects 2 values: a value, and a List of the same type. In your question, you gave it an Array of Ints. You can use the Data.List.toList function to get the type that (:) expects
> import Data.List
> show $ 1 : (toList [1, 2])
"Cons (1) (Cons (1) (Cons (2) (Nil)))"

Related

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.
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.
I've just found the answer to my problem using the partition function from the Data.Array module.
partition (_ > 0) [1, -2, 3, -4, 5, -6, -7, 8]
-- { no: [-2,-4,-6,-7], yes: [1,3,5,8] }

Erlang How can I merge Two list into tuple list

In erlang, I want to merge two list as the following
when,
A = [1, 2, 3, 4],
B= ["A1", "A2", "A3", A4],
wanted result
[{1, "A1"}, {2, "A2"}, {3, "A3"}, {4, A4}]
I've tried the following
'''
- module(test).
- export([start/0]).
start() ->
Abc = [2,3,1,4],
Bbc=["f1", "f2", "f3",f4],
ct:pal("Hello ~n"),
ct:pal("make_tuple_list ~p~n", [make_tuple_list(Abc,Bbc)]).
make_tuple_list([H1 | T1], [H2 | T2]) ->
[_ | _] = [{H1, H2} | make_tuple_list(T1, T2)].
make_tuple_list([], []) -> [].
'''
but got the systax erorr as the following
test.erl:14: function make_tuple_list/2 already defined
thanks in advance.
Try following....
-module(test).
-export([start/0]).
start() ->
Abc = [2,3,1,4],
Bbc=["f1", "f2", "f3",f4],
ct:pal("Hello ~n"),
ct:pal("make_tuple_list ~p~n", [make_tuple_list(Abc,Bbc)]).
make_tuple_list([H1 | T1], [H2 | T2]) ->
[{H1, H2} | make_tuple_list(T1, T2)];
make_tuple_list([], []) -> [].
Separator for splitting function clauses is ;. . is function definition terminator. In the above case, both occurrences of make_tuple_list are ending with ., which essentially means, in the second occurrence we are re-defining an already defined function, which is not allowed in ErLang.

How does sortWith in Scala work in terms of iterating a tuple?

A list can be iterated as follows:
scala> val thrill = "Will" :: "fill" :: "until" :: Nil
val thrill: List[String] = List(Will, fill, until)
scala> thrill.map(s => s + "y")
val res14: List[String] = List(Willy, filly, untily)
The above code first creates a list and then the second command creates a map with an iterable called as 's', the map creates a new string from 's' by appending the char 'y'.
However, I do not understand the following iteration process:
scala> thrill.sortWith((s,t) => s.charAt(0).toLower < t.charAt(0).toLower)
val res19: List[String] = List(fill, until, Will)
Does the tuple (s,t) take two elements of thrill at once and compares them? How is sorting performed exactly using this syntax/function?
Sorting is arranging the data in ascending or descending order. Sorted data helps us searching easily.
Scala uses TimSort, which is a hybrid of Merge Sort and Insertion Sort.
Here is signature of sortWith function in scala -
def sortWith(lt: (A, A) => Boolean): Repr
The sortWith function Sorts this sequence according to a comparison function. it takes a comparator function and sort according to it.you can provide your own custom comparison function.
It will perform Tim Sort on the input list to result sorted output.
Yes the function compares two elements at a time to determine their ordering.
The implementation of sortWith falls back on Java's Array.sort (docs) with the following signature
sort(T[] a, Comparator<? super T> c)
which takes in an Array of T and a comparator, equipped with a binary function that can compare any two elements of the set of possible values of T and give you some information about how they relate to each other (as in should come before, same or after based on your function).
Behind the scenes it is really just an iterative merge sort details of which can be found on the wikipedia page for merge sort
Leaving the optimizations aside, if you aren't familiar with it, merge sort, which is a divide and conquer algorithm, simply breaks down the collection you have until you have groups of 2 elements and then merges the smaller lists in a sorted way simply by comparing 2 elements at a time, which is where the binary comparison function you pass in comes to play.
i.e.
List(4, 11, 2, 1, 9, 0) //original list
Break down to chunks:
[4, 11], [2, 1], [9, 0]
Sort internally:
[4, 11], [1, 2], [0, 9]
Merge:
[1, 4, 11], [2], [0, 9]
[1, 2, 4, 11], [0, 9]
[0, 1, 2, 4, 11], [9]
[0, 1, 2, 4, 9, 11]
P.S. a nit picky detail, sortedWith takes in a Function2 (a function of arity 2). This function you pass in is used to generate what we call an Ordering in Scala, which is then implicity converted to a Comparator. Above, I have linked to the implementation of sorted which is what sortedWith calls once it generates this ordering and which is where most of the sorting logic happens.

How do I index an element from an array consisting of arrays in purescript?

a = [ 1, 2, 3]
a
[1,2,3]
b = [ 3, 4, 5]
b
[3,4,5]
c = [a ,b]
c
[[1,2,3],[3,4,5]]
a !! 2
(Just 3)
a !! 2
(Just 3)
a !! 1
(Just 2)
c !! 2
Nothing
c !! 1
(Just [3,4,5])
c !! 1 !! 0
Error found:
in module $PSCI
at line 1, column 1 - line 1, column 11
Could not match type
Maybe
with type
Array
while trying to match type Maybe (Array Int)
with type Array t0
while checking that expression (index c) 1
has type Array t0
in value declaration it
where t0 is an unknown type
Indexing into an array returns not the plain element, but values wrapped in Maybe, because the array might not have an element at the given index. In your case, the result of c !! 1 has type Maybe (Array Int). So you have to handle that Maybe somehow.
I guess you expect the end result to be of type Maybe Int. There are different ways to do so. The perhaps most explicit one is:
case c !! 1 of
Nothing -> Nothing
(Just x) -> x !! 0
(this will return Just 3)
Because "chaining" functions like this is very common, there are abstractions that lead to the same result, e.g.:
(c !! 1) >>= (_ !! 0)
Anyways, the trick is to reach into the first result (if it was successful) and then try the second indexing. If both succeed, return the end result. If one fails, return Nothing.

Standard ML permutations

I am working on a function to the permutations for all values in a list.
Here is what I have so far:
//MY ROTATE FUNCTION
fun rotate e [] = [[e]]
| rotate e (x::xs)= (e::x::xs)::(List.map (fn l => x::l) (rotate e xs));
//MY CURRENT PERMUTATION FUNCTION
fun perm [] = []
| perm (x::xs) = List.concat(List.map (fn l => (rotate x xs)) xs) # perm xs;
OUTPUT:
- perm [1,2,3];
val it = [[1,2,3],[2,1,3],[2,3,1],[1,2,3],[2,1,3],[2,3,1],[2,3],[3,2]]
The output should be something like [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]. As you can see I am missing something here. I believe the issue is my 3 is not being passed to rotate as rotate 3 [1,2] is what I am missing from my code along with two 2 element lists being here for some reason.
How can I correct my perm function to show the output correctly? Any help no matter how big or small would help me a lot.
Here is a simple fix for your attempted solution. You were nearly there.
fun interleave x [] = [[x]]
| interleave x (h::t) =
(x::h::t)::(List.map(fn l => h::l) (interleave x t))
fun permute nil = [[]]
| permute (h::t) = List.concat( List.map (fn l => interleave h l) (permute t))
I don't think that the rotate approach is the one you'll want to take. Rather, as Shivindap describes here, a good way to do this sort of this is to pull the first element from the argument list, and append it to all permutations of the tail. Rinse and repeat this for every element of the list, and you'll end up with all the permutations.
You'll find an in depth explanation of this approach here. For code samples in ML, you could also check this out.
Best of luck to you!