I'm new to haskell and can't seem to figure this out. I've been using the scalpel web scraping tool and want to concatenate a bunch of URL extensions with a URL.
For example, lets say we have scraped some URL extensions into a list of strings
result =["/contact","/content"]
and we have let
websiteURL = "www.website.com"
how do I arrive at the list ?
["www.website.com/contact", "www.website.com/content"]
map ("aaa"++) ["bbb", "ccc"]
==> [ "aaabbb", "aaaccc" ]
You want to traverse your list of extensions and apply a function to each, so some kind of map is required.
The function you want to apply is to append the websiteURL string, so the answer is:
map (mappend websiteURL) result
If you didn't know the mappend function, you could find it by searching hoogle for Monoid a => a -> a -> a.
(I'll let other people generalize to more abstract types if they want...)
Related
I am trying to implement a basic function but I'm out of practice with Haskell and struggling so would really appreciate some help. My question is specifically how to select a section of a list by index. I know how to in other languages but have been struggling
[ x | x <- graph, x!! > 5 && x!! <10 ]
I have been fiddling around with basic list comprehension similar to what is above, and while I know that isn't right I was hoping a similarly simple solution would be available.
If anyone wants more information or felt like helping on the further question I have included more information below, thanks!
type Node = Int
type Branch = [Node]
type Graph= [Node]
next :: Branch -> Graph -> [Branch]
This is the individual question for the "next" function
This is the general set up information but most importantly that the graph is represented as a flattened adjacency matric
Apologies for the two pictures but it seemed the best way to convey the information.
As pointed out in the comments !! does not give you the index of a value in the way it seems you expect. It is just an infix for getting an element of a list.
There is no way to get the index of x like this in Haskell since the x object doesn't keep track of where it is.
To fix this we can make a list of objects that do keep track of where they were. This can be achieved with zip.
zip [0..] graph
This creates a list of tuples each containing their index and the value in graph.
So you can write your list comprehensions as
[ x | (index, x) <- zip [0..] graph, index > 5, index < 10 ]
Now this is not going to be terribly fast since it still needs to go through every element of the list despite the fact that we know no element after the 11th will be used. For speed we would want to use a combination of take and drop.
drop 5 (take 10 graph)
However if we wanted to do some other selections (e.g. all even indexes), we can still go back to the list comprehension.
In this case, you could drop 5 <&> take 4. As in drop 5 x & take 4. Drop skips the first few elements and take leaves out all but the first few left after the drop.
I'm trying to learn Elixir. In most other languages i've battled with, this would be an easy task.
However, i can't seem to figure out how to access a list item by index in Elixir, which i need for finding the median item in my list. Any clarification would be greatly appreciated!
You will want to look into Enum.at/3.
a = [1,2,3,4,5]
middle_index = a |> length() |> div(2)
Enum.at(a, middle_index)
Note: This is expensive as it needs to traverse the entire list to find the length of the list, and then traverse halfway through the list to find what the actual element is. Generally speaking, if you need random access to an item in a list, you should be looking for a different data structure.
This is how I would do it:
Enum.at(x, div(length(x), 2))
Enum.at/3 retrieves the value at a particular index of an enumerable. div/2 is the equivalent of the Python 2.x / integer division.
I am using Jython execute the python code part (a python module with utility functions from existing codebase) that returns a list of tuples, but what I get in scala is a simple flattened list. Any suggestions on the cause would help.
Since I am a beginner with with Scala and Jython, this probably might not be the best approach to solve the problem. I call the python function as shown below:
val viaJython = true
val interp = new PythonInterpreter()
val pyCode =
interp.compile(
"""import myModule as df
| aList = df.find_date(foundVal)"""
)
interp.set("foundVal", foundVal)
interp.exec(pyCode)
println(interp.get("aList"))
A simple solution may be: If you get a flattened List and you know the tuple size n then it can be unflattened into a List of Lists with List.grouped(n).toList. Then the sublists can be converted to tuples with map as shown below or using methods given at Convert a Scala list to a tuple? and Is there way to create tuple from list(without codegeneration)?. If you do not know the tuple length then you can find out by examining the bytecode generated by javap -c on the class file.
Another method is to use the implicit conversions from Java collections, iterators, iterables and enumerators which Scala provides. To apply them add "import scala.collection.JavaConversions._" before executing Jython and set resulting Jython List to Scala mutable.Buffer with explicit type declaration. For example, if the Jython List elements are 3-tuples of Int (Tuple3[Int,Int,Int] in Scala) then the converted Scala collection could be defined as:
val pyBuffer: scala.collection.mutable.Buffer[Tuple3[Int,Int,Int]] = ResultingJavaListFromJython
The reason for using scala.collection.mutable.Buffer is that is the collection supported by scala.collection.JavaConversions for Java List conversion. After the conversion to mutable.Buffer is done, it can be converted to any of a number of other types of collections with its "to" functions including toList to convert it to a Scala List, e.g.:
val pyList = pyBuffer.toList
For reference see http://www.scala-lang.org/api/2.11.7/#scala.collection.JavaConversions$ or the equivilant API page for whatever version of Scala you are using.
Another issue is that Java does not have tuples so Jython implements PyTuple with java.util.List and Scala does not provide conversion to Tuple. For that reason another thing to try, assuming that each PyTuple has Int elements, is:
import scala.collection.mutable.Buffer
val pyBuffer2: Buffer[Buffer[Int]] = ResultingJavaListFromJython
Then the elements of pyBuffer2 can be mapped to tuples. For example, assuming each Buffer[Int] element has 3 elements:
import scala.collection.mutable.ArrayBuffer
val pyBuffer3 = pyBuffer2.map{case ArrayBuffer(a,b,c) => (a,b,c)}
Now pyBuffer3 can be converted to Scala List with toList as shown above.
The reason for importing scala.collection.mutable.ArrayBuffer and matching on it is that it is Scala's default implementation of mutable.ArrayBuffer which is a trait.
So I've been trying to implement this function in my module and so far I got this:
EXAMPLE 1.
[2,[3,[4,[5,[6,[7,[8,[]]]]]]]]
I am trying to figure out how I can make it look like a proper list, ie:
EXAMPLE 2.
[2,3,4,5,6,7,8].
I know I have to play with Heads and Tails but I am miserably failing at understanding it.
Any help would be appreciated.
Thanks!
Actually in the example 1 you show proper list. List that just consists of 2 elements - number and another list.
Improper list is different thing - for instance [1|2].
You can turn example 1 into example 2 by lists:flatten.
1> M = [2,[3,[4,[5,[6,[7,[8,[]]]]]]]].
[2,[3,[4,[5,[6,[7,[8,[]]]]]]]]
2> lists:flatten(M).
[2,3,4,5,6,7,8]
The root of the problem is how you have built your list. What you have here:
[2,[3,[4,[5,[6,[7,[8,[]]]]]]]]
is not one list but nested lists each of two elements. When you do [Element,List] this does NOT prepend Element to List but builds a new list with Element as the first element and List as the second element. Note that each list is a proper list but you have not built one list but nested lists.
To prepend Element to List you use the syntax [Element | List]. So:
[2|[3|[4|[5|[6|[7|[8|[]]]]]]]]
which builds the list [1,2,3,4,5,6,7,8].
So [Element | List] and [Element,List] are two very different things, the first prepends an element to the beginning of a list while the second builds a new list of two elements. There is no direct way of appending an element to a list without rebuilding the list.
Not as obvious as it looks at first, but this is a manual way of doing what lists:flatten/1 does (in this particular case, its more interesting otherwise):
proper(L) -> proper([], L).
proper(A, [H|[T]]) -> proper([H|A], T);
proper(A, []) -> lists:reverse(A).
I have a list of lists. I need the elements inside reordered so that the new list of lists is a list of all the first elements, then a list of all the second elements, etc.
It should look like this:
Input
[[a1,a2,a3],[b1,b2,b3],[c1,c2,c3]]
Output
[[a1,b1,c1],[a2,b2,c2],[a3,b3,c3]]
Can anyone help me with this?
It looks like you want transpose, for which you need to import Data.List.
transpose will take the first elements of the lists that have them and put them in the first list in the right order, then the second elements of the lists that have them and put them in the second list in the right order, and so on.
For example,
> transpose [[1,2,3],[4,5],[6]]
[[1,4,6],[2,5],[3]]
> transpose [[1],[2,3],[4,5,6]]
[[1,2,4],[3,5],[6]]
In general when confronted with such issues :
Determine the type of the function you need, here [[a]] -> [[a]]
Search Hoogle http://www.haskell.org/hoogle/
Guess first result in your case ? transpose of course.
NB : You should accept answer from user3217013 - I wrote this because I can't edit yet