Duplicates in one list to a new list - list

I have this function that takes one lists and checkes for duplicates, if any duplicates are found they are added to a new list like this:
let foo1 z list = list |> List.filter (fun e -> e <= z)
this gives foo1 1 [2;3;4;1;5;1;6;1] => [1;1;1]
the problem is that I don't want to use any of the builtin functions in f#

You asked a number of basic F# questions on list processing already, so I recommend reading some introductions first and trying it yourself.
Working with Functional Lists explains how F# lists work
Introduction to F# has a tutorial on lists and pattern matching with recursion
Using built-in functions is the right way to solve the problem in practice. If you want to learn F# and understand recursion, then read the above first. Then you should be able to write something like:
let rec duplicates z = function
// If the list is empty, return empty list of duplicates
| [] -> []
// If it starts with 'z' then return one duplicate and recursively process the rest
| x::xs when x = z -> x::(duplicates x xs)
// If it starts with something else, then skip the first element and process the rest
| x::xs -> duplicates z xs
There are many F# introductions that explain how filter and similar functions are implemented. The F# wikibook covers this topic and you'll find it in most of the F# books (see a list on fsharp.org) and Working lists section on www.tryfsharp.org covers this too.

Related

How to group by elements of tuple in Scala and map to list of new elements?

I going through some Scala exercises in order to understand better high order functions. I have the following problem, which I cant understand how to solve. I have the following list:
val input = List((1,"a"), (1,"b"), (1,"c"), (2,"d"), (2,"y"), (2,"e"), (3, "u"), (3,"a"), (3,"d"))
I want to create a Map from this list which maps each letter encountered on the input list to a list of all the numbers which were previously in the same tuple as that letter. Example output:
Map(a -> List(1,3), b->List(1), c->List(1), d->List(2,3), y->List(2), e->List(2), u->List(3)
What I have tried so far is:
val output = input.groupBy(_._2)
However this gives as output:
Map(e -> List((2,e)), y -> List((2,y)), u -> List((3,u)), a -> List((1,a), (3,a)), b -> List((1,b)), c -> List((1,c)), d -> List((2,d), (3,d)))
Could someone help me understand how I could go about solving this? I appreciate any help as I am new to functional programming
As #sinanspd said:
input
.groupBy {
case (numer, letter) => letter
} map {
case (key, list) => key -> list.map {
case (number, letter) => number
}
}
// Or equivalently
input.groupBy(_._2).view.mapValues(list => list.map(_._1)).toMap
// Or even simpler if you have access to Scala 2.13
input.groupMap(_._2)(_._1)
Every time you want to transform some collection of values where the transformation is one to one, you just need a map, so in this case, you want to transform the values of the Map returned by the groupBy, which are Lists, and then you want to transform every element of those Lists to just return the first component of the tuple. So it is a map inside another map.
Also, the Scaldoc is your friend. Usually, there are many useful methods, like mapValues or groupMap.
Here is a more detailed explanation of my comment. This is what you need to do:
val output = input.groupBy(_._2).mapValues(_.map(_._1))
It is important to remember in functional programming we love pure functions. Meaning we will not have shady side effects and we like to stick to one function one purpose principle
This allows us to chain these pure functions and reason about them linearly. Why am I telling you this? While your instinct might be to look for or implement a single function to do this, don't
In this case, we first groupBy the key, and then map each value where we take the value List and map it to extract the _._1 of the tuple.
This is the best I could do, to make it sorted too , as I see the other responses are not sorted , maybe someone can improve this too:
import scala.collection.immutable.ListMap
ListMap(input.groupBy(_._2).mapValues(_.map(_._1)).toSeq.sortBy(_._1):_*)

How to find inside a list of lists a list with a single element

I have been trying to do a function that returns to me the first (or all it might work to but I do prefer just the first), element of a list of lists that is single, i mean:
[[x;y;z];[a;b;c];[a];[b]]
In this case I would like to get returned the a or [a] but I cant I tried to do a function something like:
let rec find_unit ll =
match ll with
| [x] -> [x]
and so on...
But every time I try something like this, I get in a recursion that never stops, or the function simple dont return the element. Can someone tell me how to do it properly? I still cant understand a lot of OCaml syntax... Just like in the example I dont know that to put in the line of |[x] -> [x], particularly the first [x].
Sorry for the question but I am destroying my code now and I cant find a solution.
Try decomposing your problem into smaller subproblems.
(1) Your problem overall looks like an instance of the more general 'find'-problem, which has already been solved. See the standard function List.find or (if you want to find them all... List.find_all. Both functions need a predicate to pick the right element(s) from the list.
(2) You need a way to determine if some list is a singleton. It's easy, use pattern-mathing.
let is_singleton xs = function
| [_] -> true
| _ -> false
(3) Now, combine the above and you'll get a solution.
A couple of observations on the code you give:
Your pattern needs to match the whole string ll, but the pattern you give seems to be intended to match just one element of ll. A pattern more like [x] :: rest is going to work better.
The way to avoid infinite recursion is always the same. First, make sure you check for the smallest possible input (the basis). For your problem this will be the case when ll is an empty list. Second, if you haven't found what you're looking for, continue the search on a smaller problem. In your case this will mean searching the tail of your list.
You also need to decide what to do when there is no element of the list like the one you're looking for. If you return [x] when you find it, you could return [] (say) if you don't find it. Or you could raise an exception like Not_found.
(As a side comment, lists and arrays are different things in OCaml. I removed the array tag, as your question seems to be about lists.)
Well all answers here helped me find a way to get the solution, and I am going to put it here because it might help someone else.
I used the function:
let is_single xs = function
| [_] -> true
| _ -> false
to do: let teste xs = List.filter(fun inner ->(is_single inner)inner)xs;; This teste function is returning to me a List of Lists with all single elements, so to get only one element inside of that lists i did: List.hd(List.hd teste xs)

Taking list of tuples as parameters in Haskell

I would like to know how to take a list of tuples as a parameter or if there is an easier solution.
I am new to Haskell (only started a week ago) and I made this function to check if the tuple acts as a Pythagorean Triple.
pyTheorem (a,b,c) = a ^ 2 + b ^ 2 == c ^ 2
let x = pyTheorem (3,4,5)
So how would I define a function where it takes a list of tuples and returns the tuples that are Pythagorean Triples? Also, if there is a better way of doing this, please elaborate.
I looked up some similar questions but I couldn't find something that seemed to fit this example.
Side Note: I find that some of the examples in LYAH I can't seem to use in the online terminal: https://ghc.io/
So I am using http://www.tutorialspoint.com/compile_haskell_online.php instead. Are there any big differences I should be aware of?
Thanks.
I think is all you need
filterPy : [(Int,Int,Int)] -> [(Int,Int,Int)]
filterPy ls = filter pyTheorem ls
Real afficionados would also write it 'point free'
filterPy = filter pyTheorem

Pattern matching on complex data structures ocaml

I am completely new to OCaml, so I am having some trouble with the basics. For my program, I have to match a nucleotide with it's complement (G -> C, C -> G, A -> T, T -> A) in order to find the other half of the double helix. The general idea is that DNA is composed of 2 complementary helixes, each of which is a sequence of nucleotides. Currently, I am trying to compute the other half of the double helix.
So far, I have represented the nucleotides with an enumeration and I've represented the DNA with a nucleotide list which corresponds to one helix.
type nucleotide =
| G
| C
| A
| T
type helix = nucleotide list
let rec complementary_helix (x:helix): helix =
| [G] -> [C]
| [C] -> [G]
| [A] -> [T]
| [T] -> [A]
end
I know something is missing here, but I don't know how to go about it. Can somebody steer me in the right direction?
You're basically just missing List.map:
let complement = function
| G -> C
| C -> G
| A -> T
| T -> A
let complementary_helix (x: helix) : helix =
List.map complement x
(For what it's worth, it's not necessary to specify types. OCaml will infer the types. It's good style to specify them for documentation but maybe not if they're obvious.)
Edit
OK, I guess this is a homework problem in which you're supposed to use recursion to solve the problem.
The way to think of recursion is that you want to solve a little piece of the problem, which gives you a smaller problem to solve. You pass the smaller problem to yourself (either before or after you solve your little piece). You also need to know when the problem has gotten so small there's no more work to do on it.
In your case, the little piece would be to translate one nucleotide to its complement. You're doing that semi-OK (you have lists where you would really just want to work on single nucleotides). But you're not passing the remainder of the problem to yourself to solve recursively. You're also not checking whether the problem is so small there's nothing to do.
For functions on lists, around 99% of the time you're going to make the problem smaller by splitting the list into the head (a single element) and the tail (a list that's smaller by one). That will work for you here.
Edit 2
As an example of how list recursion looks, here's a function that adds up all the integers in a list:
let rec sum l =
match l with
| [] -> 0
| head :: tail -> head + sum tail
This has all the parts I described. The match is used both to tell when the problem is trivial (when the list is empty) and to split the list into the head and the tail. Assuming you had the sum for the tail (which you can get recursively), the answer is pretty obvious. You just need to add the head onto this sum. You just need to ask yourself (almost always): if I had the answer for the tail of the list, what would I need to do to combine it with the head?

How to make a list of lists in prolog

I use SWI-Prolog and I want to make a list of several other lists.
For example, I want to put the following three lists
[a,b,c]
[1,2]
[d]
into a larger one that looks like [[a,b,c],[1,2],[d]] .
divideList([]):-!.
divideList([Head|Tail]):-
list_to_set(Head,H),%H is a List
divideList(Tail).
I want to put all H in one list.
How can I do this?
The problem is that you are not using H in your predicate to put the list you want
This should do it
divideList([], []):-!.
divideList([Head|Tail], [H|HTail]):-
list_to_set(Head,H),%H is a List
divideList(Tail, HTail).
The second argument will have your list of lists.