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
Related
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):_*)
I could not find any size or len function in the official documentation. What is a simple way to find the number of elements in a map created using:
module M = Map.Make(String)
I am looking for something like M.size M.empty : 0.
The function that you're looking for is called cardinal (as in the cardinality of a set).
Example:
module M = Map.Make(String)
let m = M.singleton "x" "y"
let () = Printf.printf "%d\n" (M.cardinal m)
This will print 1, as there is exactly one binding.
hoogle4ocaml ": 'a t -> int$" | grep -i map
Would tell you:
~/.opam/4.05.0/lib/ocaml/map.mli: val cardinal: 'a t -> int
Cf. https://github.com/UnixJunkie/hoogle_for_ocaml
So, the short answer is:
Map.cadinal your_map
PS: and yes, the OCaml community is still dearly missing the equivalent of Hoogle in the Haskell community. There are some hacks around, like the one I just linked, but we would need a serious one, correctly working, actively maintained and largely vetted by the community
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)
I'm new to OCaml,and have just found an on-line OCaml guide, http://try.ocamlpro.com/.
When it comes to lesson 5, I get trapped in some exercises. So, here is the problem:
fix all these let expressions in order to get the expected result at the end:
1.
let xy =
let x = 'x' and let y = 'y' in x ::[y]
2.
let ab =
let a = 'a'
let b = 'B' in Char.lowercase b
in a ::[b]
3.
let up = Char.uppercase in
big_xy = List.map up xy ;
big_ab = List.map up ab ;
big_ab # big_xy
PS:I know how to solve problem 1,and I post it here for the need of problem 3.For Problem 2 and 3,I can see where the problem is,but I can hardly figure out how to fix it.I'm a little confused about the compact "let...in" statement,and there is few resource I can refer to for such problem.
This is a completely wrong OCaml, indeed it is not an OCaml at all))
I'm just trying to guess what was your intention, so in the second code sample you have tried to bind to variables to some character values, then lowercase one of them and create a list of this two values.
Before you can understand, what is wrong with your code, you need to know something about OCaml's grammar.
There're several kinds of binding statements in OCaml, the first one is an expression and has the following pattern:
let «variable-name» = «expr-1» in «expr-2»
This means that you bind the result of evaluating «expr-1» to a «variable-name», so that you can use it inside «expr-2» (and only in «expr-2», it is its scope). «expr-2» can be another binding-expression on its own. Let's take some examples:
let a = 'a' in [a]
or
let a = 'a' in
let b = 'b' in
[a; b]
The second kind of bindings is a so called top-level binding, that is used when you're adding some definition to a module level (or an interactive top-level, that is the same). They look a little bit simplier, but they're not expressions. When I say that something is not an expression, I mean, mostly, that it can't be evaluated to a value. So, they have the following pattern:
let «variable-name» = «expr»
As you can see, there is no in part, only raw binding. You can use this statement to create a global constant, e.g.,
let pi = 4. *. atan 1.
Or, you can use it to bind a function to a name (in other words to write a function definition):
let circle_area radius = pi * radius ** 2.
Of course, inside a function you can use any expressions, including a binding expression:
let area_of_circles radii =
let areas = List.map circle_area radii in
List.fold_left (+.) 0. areas
I would like to note, that there're lots of good tutorials and textbooks, that can help you to learn OCaml very fast. You can find them at the OCaml tag page. I, personally, would suggest you to look at the 'OCaml from the very beginning' book.
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.