Haskell Convert String to nested lists - list

I have a doubt, is there a function in haskell that can help me solve this? I'm trying to receive as an input a String with the form of a list and the convert it into an actual list in haskell
for example:
convert "[ [1,1] , [2,2] ]" into [ [1,1] , [2,2] ]
Example 2:
convert "[ [ [1,1], [1,1] ], [ [2,2] , [2,2] ] , [ [1,1] ,[1,1] ] ]"
into [ [ [1,1], [1,1] ], [ [2,2] , [2,2] ] , [ [1,1] ,[1,1] ] ]
thanks in advance!

Yes, that function is read. If you specify what it should read in a type annotation, you will get the desired result, provided there is an instance of Read for that type.
read "[ [1,1] , [2,2] ]" :: [[Int]]
-- [[1,1],[2,2]]
read "[ [ [1,1], [1,1] ], [ [2,2] , [2,2] ] , [ [1,1] ,[1,1] ] ]" :: [[[Int]]]
-- [[[1,1],[1,1]],[[2,2],[2,2]],[[1,1],[1,1]]]

One option could be to use the Aeson package and treat the text as json data.
Prelude> :set -XOverloadedStings
Prelude> import Data.Aeson
Prelude Data.Aeson> jsString = "[ [ [1,1], [1,1] ], [ [2,2] , [2,2] ] , [ [1,1] ,[1,1] ] ]"
Prelude Data.Aeson> decode jsString :: Maybe [[[Int]]]
Just [[[1,1],[1,1]],[[2,2],[2,2]],[[1,1],[1,1]]]

Related

How to rotate letters in a list of strings while preserving the strings' shapes?

I am trying to write a function join :: [[a]] -> [[a]] that joins the last character of a list within a list with the first character of a list within a list.
join ["m"] = ["m"]
join ["a","b","c"] = ["b","c","a"]
join ["goodday", "world", "i", "love", "haskell"] = ["ooddayw","orldi","l","oveh","askellg"]
join ["the", "catcher", "in", "the", "rye"] = ["hec","atcheri","nt","her","yet"]
I am trying to write a code that does the above using only the basic functions in Haskell (no library functions), and only using recursion.
However, I cannot seem to achieve a piece of code that works appropriately. This is the code that I have so far:
join :: [[a]] -> [[a]]
join [[a]] = [[a]]
join (n:ns:nss) | null nss == False = ((i n ns) : k (ns:nss))
| otherwise = []
Is it possible to do this?
Here's a solution with higher-order functions, working in the whole data-manipulation paradigm:
import Control.Applicative (liftA2)
import Data.List (unfoldr)
import Control.Arrow ( (>>>) )
rotateds :: [[a]] -> [[a]]
rotateds =
map (splitAt 1) -- 1., 2.,
>>> concatMap (\(a,b) -> [a,b]) -- 3.,
>>> liftA2 (++) (drop 1) (take 1) -- 4.,
>>> unfoldr (Just . splitAt 2) -- 5.,
>>> takeWhile (not . null) -- 5.,
>>> map (\[a,b] -> (++) a b) -- 6.
It passes all your tests. So yes it is possible. How it works is:
1. turn each sublist in the input [ [a,b,c,...] , [d,......] , ... ]
2. into a pair [ ([a],[b,c,...]) , ([d], [...]) , ... ]
3. splice'em in [ [a],[b,c,...] , [d], [...] , ... ]
4. move the first letter over [ [b,c,...] , [d], ........ [a] ]
5. and restore the structure back to how it was
by reconstituting the pairs [ [[b,c,...] , [d]], ........... ]
6. and appending them together [ [ b,c,... , d ], ........... ]
Converting it to straight manual recursion is a torturous task is left as an exercise for an avid learner.

How to use Numpy Tile function To get this result

I want to broadcast the array in a give fashion.I now tile() function in numpy can be used for broadcasting i tried it but not able to generate the required output.
input=[ [1,2],
[3,4],
[4,5] ] #shape(3X2)
numpy.tile(input,----)
out put= [ [ [1,2],
[1,2]
],
[ [3,4],
[3,4]
],
[ [4,5],
[4,5],
]
] #shape(3,2,2)
One approach with np.repeat -
np.repeat(a,2,axis=0).reshape((a.shape) + (2,))
Another one with np.repeat -
np.repeat(a[:,None],2,axis=1) # Or use np.newaxis in place of None
With np.tile -
np.tile(a,2).reshape((a.shape) + (2,))
Another option is to stack input with itself and transpose
np.stack([input] * 2).transpose(1, 0, 2)
array([[[1, 2],
[1, 2]],
[[3, 4],
[3, 4]],
[[4, 5],
[4, 5]]])

Haskell algorithm for sequence of tuples in a list of lists

I was playing around a bit in Haskell to get familiar with it, but got stuck at the following problem:
I want to define a function that, given a list containing some amount of other lists, each containing 0 or more tuples, creates a new list as following:
*Main> foo
[
[ (1,2), (3,4) ],
[ (5,6) ],
[ (7,8), (9,10) ]
]
= [
[ (1,2), (5,6), (7,8) ],
[ (1,2), (5,6), (9,10) ],
[ (3,4), (5,6), (7,8) ],
[ (3,4), (5,6), (9,10) ]
]
So, in other words, the function should compose a list with every tuple from the first list combined with in each case one of the other tuples in the N remaining lists.
I was trying to write a recursive algorithm for this, but can't wrap my head around dealing with the N amount of other lists to combine tuples with. For just two lists of tuples, I would write something like:
composeList [] _ = []
composeList (x:xs) list = composeTuples x list ++ composeList xs list
composeTuples _ [] = []
composeTuples t (x:xs) = [t,x] : composeTuples t xs
This gives me:
*Main Data.List> composeList [(1,2),(3,4)] [(5,6),(7,8)]
[
[ (1,2), (5,6) ],
[ (1,2), (7,8) ],
[ (3,4), (5,6) ],
[ (3,4), (7,8) ]
]
Though I can't seem to put the pieces together and make it work for any number of lists, each with any (>=0) number of tuples.
I'm both interested in solving this issue with some of Haskell's predefined functions (if possible), as well as with a somewhat similar approach as the one I was going for in the example above.
Thanks in advance!
This is simply the list monad, selecting an element from each list non-deterministically.
The function you're looking for is sequence :: Monad m => [m a] -> m [a] from Control.Monad
λ. let as = [(1,2),(3,4)]
λ. let bs = [(5,6)]
λ. let cs = [(7,8),(9,10)]
λ. let xss = [as, bs, cs]
λ. sequence xss
[[(1,2),(5,6),(7,8)]
,[(1,2),(5,6),(9,10)]
,[(3,4),(5,6),(7,8)]
,[(3,4),(5,6),(9,10)]
]
Here's a recursive solution
solution :: [[a]] -> [[a]]
solution (x: xs) = [y: ys | y <- x, ys <- solution xs]
solution [] = [[]]
The idea behind the solution is the following: prepend each element of the head of list to every list you get from recursively computing the result for the tail of the input list.

check/2 predicate in prolog that will have sorted list of lists

I am new to prolog and I am trying to create a simple predicate which will have sorted list of lists from a unsorted list of lists. check(A,B).
check( [ [], [1], [1,1] ], [ [], [1,1], [1] ] ). returns true
check( [ [], [1], [1,1] ], [ [1,1], [1] ] ). returns false.
Note that even if A is sorted it should only contain elements from B and not anything more or less.
How do I implement this without any built in prolog predicates?
A list of lists is essentially a tree structure: you just walk the tree. Something like this:
validate( [] , _ ) .
validate( [X|Xs] , Valids ) :-
exists_in( X , Valids ) ,
validate( Xs , Valids )
.
exists_in( X , [X|Xs] ) :- !.
exists_in( X , [_|Xs] ) :- exists_in( X , Xs ) .

read file lines with spaces into NetLogo as lists

How can I have file contents separated by spaces read into NetLogo as a list?
For example, with a file containing data such as these:
2321 23233 2
2321 3223 2
2321 313 1
213 321 1
I would like to create lists such as these:
a[2321,2321,2321,213]
b[23233,3223,313,321]
c[2,2,1,1]
Well, here is a naive way to do it:
let a []
let b []
let c []
file-open "data.txt"
while [ not file-at-end? ] [
set a lput file-read a
set b lput file-read b
set c lput file-read c
]
file-close
It assumes the number of items in your file is a multiple of 3. You will run into trouble if it isn't.
Edit:
...and here is a much longer, but also more general and robust way to do it:
to-report read-file-into-list [ filename ]
file-open filename
let xs []
while [ not file-at-end? ] [
set xs lput file-read xs
]
file-close
report xs
end
to-report split-into-n-lists [ n xs ]
let lists n-values n [[]]
while [not empty? xs] [
let items []
repeat n [
if not empty? xs [
set items lput (first xs) items
set xs but-first xs
]
]
foreach (n-values length items [ ? ]) [
set lists replace-item ? lists (lput (item ? items) (item ? lists))
]
]
report lists
end
to setup
let lists split-into-n-lists 3 read-file-into-list "data.txt"
let a item 0 lists
let b item 1 lists
let c item 2 lists
end