Combining elements of a sublist of a list - list

I have the following list of sublists
[[1;5;10];
[2;6;11];
[3;7;12]];
I am trying to a create the following list of sublists:
[[1;2;3];
[5;6;7];
[10;11;12]]
The first sublist of the result should containt the first element of each original sublist, second result sublist should contian the second elements of each of the original sublists and so on.
Each sublist contains the same number of elements as the other sublists. The amount of sublists is at least 2.
I was thinking of using List.map but I am not sure what function to apply to each sublist to exctract the needed elements.
This is what I have so far:
let rec compute list =
List.map (fun x -> ) list
Any suggestions are appreciated!

Here you need two recursions (as you would need 2 imbricated loops in an imperative language).
The first recursion should allow you to go through the inputs line, say from 1 to 3, and at each step of this recursion, you will need a second recursion,to go along the full row.
You can either do it all by hand or you can use List.fold_left. (I would use fold for the inner recursion.

Related

find last element of a list in haskell

I wrote the following code to find the last element of a list in haskell:
myLast (x:xs) = do
ret <- if xs == [] then x else (myLast xs)
return ret
The idea is to traverse the list until we are at an element which has the empty list as its next element. When we find it we set ret to that element.
It makes sense for me but when I run the code inside the interactive shell I get the following error:
<interactive>:1:1: error:
• No instance for (Num (m0 b0)) arising from a use of ‘it’
• In a stmt of an interactive GHCi command: print it
edit 1
The reason I used do was because I saw that pattern being used somewhere to also traverse a list, so I thought I could do the same here. I'am avoiding libraries for now to get comfortable with the language.
I wrote the function avoiding the do keyword and now it works:
myLast(x:xs) = if xs == [] then x else (myLast xs)
There's now just an issue with the empty list case. How to approach this in haskell?
let's start with the signature of your function
myLast :: [a] -> a
now, for an empty list input, what can be expected as the output? How you can make up an instance of an arbitrary type a?
Alternatively, you can defer the handling of missing last element to the callers of your function.
myLast :: [a] -> Maybe a
You want
myLast (x:xs) =
to be equal to
if xs == [] then x else (myLast xs)
Great, xs == [], so let's just put it back in:
myLast (x:[]) = x
but what about the else part? Well, let's add another equation for that,
myLast (_:xs) = myLast xs
and we're golden.
What if we call it with an empty list [] though? No definition case will match, and we will get some kind of a run-time error. Well, same thing happens with the built-in function last too, so we're no better and no worse than Haskell itself here.
What is that match that I mentioned, you ask? That's how Haskell functions get invoked. Each function definition can have several clauses, starting with the function's name, and containing a pattern for each expected argument.
In a left hand side of an equation,
(x:[]) is a pattern, matching any singleton list. It can also be written [x]. x will refer to the list's only element, if used in the right-hand side of the equation.
[] is a pattern, matching any empty list.
(x:xs) is a pattern, matching any non-empty list. x will refer to the list's head (i.e. first) element, if used in the right-hand side of the equation; and xs will refer to the rest of the elements in a list (which are also, a list -- also known as its tail).
But wait, you ask. Wouldn't both clauses match for a singleton list, the first for the pattern [x] and the second for (_:xs) with xs matched up with an empty list, []?
Why yes, they both would match indeed; (x:[]) and (_:xs) are not mutually exclusive.
But that's OK, because in Haskell, if the first clause has matched, that's it -- that is the clause that gets executed, and no other attempts at any additional pattern matching and clause selection are made.
That would be Prolog, and that's quite another language.

Python - iterate over two lists and find matches and position of mis-matches

I am working in Python 2.7
I am trying to iterate over 2 lists, of un-equal length, and I want to create a new list, containing the matching elements (same elements in the same position), and when the elements do not match, I need to have some text as well as the position of the miss-matching elements.
list1=[1,2,3,4]
list2=[1,2,3,5,6]
This outputs the matches
match=[[b] for a, b in zip(list1, list2) if a==b]
result:
[1,2,3]
But I do not know, in a one-liner, how to also flag the mis-matches:
[1,2,3,"nomatch-pos4"]
or
[1,2,3,"nomatch-pos4","nomatch-pos5"]
It does not matter if it will iterate over the maximum or minimum of the 2 list lengths.
it first find the minimum of the two lists and iterate over the shorter list and check if an element in the list matches with other list in same position. check below code:
match = [list1[i] if list1[i] == list2[i] else 'nomatch-pos'+str(i+1) for i in range(0,min(len(list1),len(list2)))]

SML pair tuples conversion

I've been trying to solve this pair tuples problem where the input is a list of tuples and the output is a tuple of lists where the first element of each tuple is grouped together and similarly with the second (i.e. [(1,2),(3,4),(5,6)] --> ([1,3,5],[2,4,6])).
I've thought of this code but it gives me an error:
fun convert L = foldl (fn ((x,y),(u,v)) => ((u#x),(v#y)) ([],[]) L;
Any suggestions for a fix?
Concatenation (#) takes two lists, but x and y are values, so you need to wrap them with [] to make a single-element list:
fun convert l=foldl (fn((x,y),(u,v))=>(u#[x],v#[y])) (nil,nil) l
You can use cons instead of concatenation, though the lists inside the returned tuple are reversed:
fun convert l=foldl (fn((x,y),(u,v))=>(x::u,y::v)) (nil,nil) l
# concatenates lists (and x and y are not lists).
Try (u#[x],v#[y]).
Note, however, that appending is a linear-time operation, while prepending (i.e. x::u) is constant. As Alex pointed out, this will build your lists in reverse, but you can resolve this by processing your input in reverse as well - i.e., by using foldr instead of foldl.

Prolog problem help

I am trying to learn prolog and have come across a problem that I can't figure out. The problem is to write a prolog predicate that takes all the numbers of a list that are less than a given number and put them into a list that will be returned. For example:
input:
findNum(5, [5, 3, 5, 6, 4, 5], Y)
output:
Y = [3, 4]
Everything I've tried seems to fail. So any help would be much appreciated. Thanks.
To solve this, you will use a typical Prolog pattern of examining the elements from your input list one-at-a-time. Prolog includes a syntax for selecting the head element from a list, by unifying the list with [A | B] , the first element of the list is unified with A and the remainder of the list (or emptiness if no elements remain) is unified with B.
You should consider first how many clauses you will need. You will need one clause to handle the case of an empty list, which is also the termination condition for your recursion. Each time you examine one item of the list, you recursively examine the remainder of the list. On the final examination, the 'remainder of the list' is empty.
For the clauses which examine the head element of the list, you have two possible conditions: the element satisfies your search criterion (less than 'num'), or it does not. To represent this, implement two clauses, both of which iterate over the list, but only the first of which matches your search criteria. The clause which detects "matching" elements must be written first in your Prolog file so that it will be considered first.
% This clause is for the "empty input" case which is also used to
% discontinue the recursion when finished.
findNum( _, [], []).
% This clause completes only if the first input element is less than
% 'M'. If the clause completes, the first input element ('X') is unified
% with the output list ([X | Y]).
findNum( M, [X | L], [X | Y]) :-
X < M,
findNum(M, L, Y).
% This clause completes if the above clauses do not. Much like an "else"
% case, this clause simply removes the first input element from the list,
% the element must not match in the search clause above and so we will now
% discard it. Thus, it is unified with the "throw away" variable named "_"
findNum( M, [_ | L], Y) :-
findNum(M, L, Y).

Filtering list of tuples

New to Haskell and have a stumbling block. I'm trying to filter a list of tuples based on the first item.
filter (==(x,_)) lis
I get an illegal '_' error, but I'm not sure how I can get around it?
In Haskell, you cannot iterate over a tuple like you can a list.
If the tuple only has two items, you can use fst to retrieve the first item of the tuple and snd to retrieve the second item.
One way to do what I think you want to do is this approach:
Prelude> let lst = [(1,2), (3,4)]
Prelude> filter ((==1).fst) lst
[(1,2)]
Which only returns the items in the list where the first element is equal to 1; of course, you can substitute x where I put 1.
To be a little more specific, (==1).fst first applies fst to the element in lst, then applies (==1) to the result of fst -- technically, the dot composes the two functions together.
You can't give an argument with a wildcard _ in it to the == operator (or to any other function). The argument needs to be a real value, not a pattern that should be matched against.
If you want to use pattern matching you could use a lambda function as you filter condition:
filter (\(a,_) -> a == x) lis
Also, there is the predefined function fst to extract the first element of a two-element tuple. This can be combined with == to do the same test:
filter ((== x) . fst)) lis