I wrote a Haskell function to generate a list of tuples.
defineIndices :: Int -> Int -> [(Int,Int)]
defineIndices n m = [(i,j) | i <- [1..n], j <- [1..m]]
The function has the following behaviour.
λ> defineIndices 2 3
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3)]
It turns out that I require the function which behaves as the following:
λ> defineIndices2D 2 3
[[(1,1),(1,2),(1,3)],[(2,1),(2,2),(2,3)]]
In which defineIndices2D returns a list of list of (Int,Int) with dimensions n*m. I am a little bit stuck here, and I was wondering how my existing solution could be altered to produce a list of a higher order.
My end goal is to generate a list of x,y indices to use as the key for values in a Data.Map Map.
You can nest list comprehension, you thus make an outer list comprehension which will enumerate over the value for m, and you each time yield a list you produce with another list comprehension expression:
defineIndices2D :: Int -> Int -> [[(Int,Int)]]
defineIndices2D n m = [ [(i,j) | j <- [1..m]] | i <- [1..n]]
For a 2×3 grid, this thus produces:
Prelude> defineIndices2D 2 3
[[(1,1),(1,2),(1,3)],[(2,1),(2,2),(2,3)]]
Related
I am trying to generate a list of perfect squares between 2 values i and n using recursion and guards. I can achieve this with list comprehension (i is not taken as an argument):
isPerfectSquare :: Integral a => a -> Bool
isPerfectSquare n = sq * sq == n
where sq = floor(sqrt(fromIntegral n :: Double))
squares :: Int -> [Int]
squares x = [y | y <- [1..x], isPerfectSquare y]
But I'm having trouble using recursion and guards for this. I'm trying to implement this without using higher order functions or list comprehension. I would appreciate someone pointing me in the right direction.
The usual trick is to generalize the task: instead of producing the squares in 1..x, produce those in a..b. This means writing an auxiliary function that takes both a and b as arguments.
Here's some skeleton code, to be adapted as needed.
squares :: Int -> [Int]
squares x = squaresFromTo 1 x
squaresFromTo :: Int -> Int -> [Int]
squaresFromTo a b
| a > b = ... -- no squares here!
| good a = ... -- keep a
| otherwise = ... -- discard a
where
otherSquares = squaresFrom (a+1) b
Now the question becomes: "how can we compute the squares in a..b knowing the recursive result otherSquares of the squares in a+1..b ?"
Please jump to edit:
I have to deal with a problem in my homework, maybe I am completely wrong on that one but I'm new to functional programming.
I have a 5x5 Matrix with Strings in it, I want to read them out, transform them to a data element and applying it to a new matrix.
I am using a recursive approach because I want to add the position of the String into the Data element!
here is what I tried:
cycleMatrix :: Int -> Int -> [[String]] -> [[Data]]
cycleMatrix 0 0 matrix = (strToData 0 0 (matrix !! 0) !! 0))
cycleMatrix n 0 matrix = (cycleMatrix (n - 1) 0 matrix):(strToData n 5 ((matrix !! n) !! 5))
cycleMatrix n m matrix = (cycleMatrix n (m - 1) matrix):(strToData n n ((matrix !! n) !! m))
with strToData I am geting the string from the matrix and passing the x and y returning a Data Object (thats working)
At the moment I am just trying to add every element to an Array but I really want to start a new list every time I am getting to zero on m (after cycleMatrix n 0 matrix)
My questions are: Is this the way to go and how do I append this element in a correct way?
Edit: Okay I finally got it to work by splitting the functions(thx to Rudi for telling me not to do everything at once)
But my questions still stands. I now have 8 lists full with Data elements
I can append them all to a List with [] ++ [], but is there a way to create a matrix out of the lists like [] : [] (adding a list as element to a list)?
I would tackle this problem by enumerating the inner lists into (x, data) tuples¹, then enumerate this enumeration into (y, [x-lists]). This then is the starting point to convert this into the desired format.
You can load this file in ghci with :load file.hs, and play with the different functions there.
¹from your edit I guess that this is what you already did
example :: [[String]]
example = [
["as", "df", "ghj"],
["xx", "yy"]
]
-- add a position number to each list element. Beware
-- that this starts with 1
enumerate :: [a] -> [(Int, a)]
enumerate = zip [1..]
-- does the enumeration, but does not transform the
-- data into the desired format. I put it here, so that
-- the functionality of the different functions is
-- better to understand.
kindofEnumarate2d :: [[a]] -> [(Int, [(Int, a)])]
kindofEnumarate2d = enumerate . map enumerate
-- convert a row of (y, [(x, value)]) tuples into a
-- [((x,y), value)] list
helper :: (Int, [(Int, a)]) -> [((Int, Int), a)]
helper (y, xs) = [((x, y), s) | (x, s) <- xs]
-- transform each row of the "kind-of" transformed
-- rows into the desired format.
enumerate2d :: [[a]] -> [[((Int, Int), a)]]
enumerate2d = map helper . kindofEnumarate2d
As a short exercise in using Haskell arrays I wanted to implement a function giving the first n (odd) prime numbers. The code below (compiled with GHC 7.10.3) produces a loop error at runtime. "A Gentle Introduction to Haskell" uses recursive calls in array creation to compute Fibonacci numbers (https://www.haskell.org/tutorial/arrays.html, 13.2, code below for reference), which works just fine. My question is:
Where is the difference between the two ways of recursive creation? Which recursive calls are generally allowed when creating arrays?
My code:
import Data.Array.Unboxed
main = putStrLn $ show $ (primes 500)!500 --arbitrary example
primes :: Int -> UArray Int Int
primes n = a
where
a = array (1,n) $ primelist 1 [3,5..]
primelist i (m:ms) =
if all (not . divides m) [ a!j | j <- [1..(i-1)]]
then (i ,m) : primelist (succ i) ms
else primelist i ms
divides m k = m `mod` k == 0
Code from "A Gentle Introduction to Haskell":
fibs :: Int -> Array Int Int
fibs n = a where a = array (0,n) ([(0, 1), (1, 1)] ++
[(i, a!(i-2) + a!(i-1)) | i <- [2..n]])
Thanks in advance for any answers!
Update: I think I finally understood what's going on. array is lazy on the list elements, but is unnecessarily strict on its spine!
This causes a <<loop>> exception, for instance
test :: Array Int Int
test = array (1,2) ((1,1) : if test!1 == 1 then [(2,2)] else [(2,100)])
unlike
test :: Array Int Int
test = array (1,2) ((1,1) : [(2, if test!1 == 1 then 2 else 100)])
So, recursion works as long as it only affects the values.
A working version:
main :: IO ()
main = do
putStrLn $ show $ (primes 500)!500 --arbitrary example
-- A spine-lazy version of array
-- Assumes the list carries indices lo..hi
arraySpineLazy :: (Int, Int) -> [(Int, a)] -> Array Int a
arraySpineLazy (lo,hi) xs = array (lo,hi) $ go lo xs
where
go i _ | i > hi = []
go i ~((_,e):ys) = (i, e) : go (succ i) ys
primes :: Int -> Array Int Int
primes n = a
where
a :: Array Int Int
a = arraySpineLazy (1,n) $ primelist 1 (2: [3,5..])
primelist :: Int -> [Int] -> [(Int, Int)]
primelist i _ | i > n = []
primelist _ [] = [] -- remove warnings
primelist i (m:ms) =
if all (not . divides m) [ a!j | j <- [1..(i-1)]]
then (i ,m) : primelist (succ i) ms
else primelist i ms
divides m k = m `mod` k == 0
Arguably, we should instead write a lazier variant of listArray instead, since our array variant discard the first components of the pair.
This is a strictness issue: you can't generate unboxed arrays recursively, only boxed (regular) ones, since only boxed ones have a lazy semantics.
Forget arrays, and consider the following recursive pair definition
let (x,y) = (0,x)
This defines x=0 ; y=0, recursively. However, for the recursion to work, it is necessary that the pair is lazy. Otherwise, it generates an infinite recursion, much as the following would do:
let p = case p of (x,y) -> (0,x)
Above, p evaluates itself before it can expose the (,) pair constructor, so an infinite loop arises. By comparison,
let p = (0, case p of (x,y) -> x)
would work, since p produces the (,) before calling itself. Note however that this relies on the constructor (,) not evaluating the components before returning -- it has to be lazy, and return immediately leaving the components to be evaluated later.
Operationally, a pair is constructed having inside tho thunks: two pointers to code, which will evaluate the result later on. Hence the pair is not really a pair of integers, but a pair of indirections-to-integer. This is called "boxing", and is needed to achieve laziness, even if it carries a little computational cost.
By definition, unboxed data structures, like unboxed arrays, avoid boxing, so they are strict, not lazy, and they can not support the same recursion approaches.
I have the following tuple representing a 2D matrix in Haskell
let a =[(1,2,3),(4,5,6),(7,8,9)]
How can I access each index individually? (e.g. a[1][1], a[0][1] etc.)
Is there a better way to interpret 2D arrays in haskell?
Here's an example of how to create and index an immutable 2D array using the standard Data.Array module:
Prelude> import Data.Array
Prelude Data.Array> let a = array ((0,0),(2,2)) [((i,j),3*i+j)| i <- [0..2], j <- [0..2]]
Prelude Data.Array> a ! (1,1)
4
More information can be found on the Haskell Wiki.
If you're going to be doing this a lot --- working with matrices, arrays, etc. --- then it's probably best to follow one of Mikhail's suggestions.
If you're simply curious about how to go about doing this though, it basically comes down to pattern matching. One thing you can do is use the !! function to get a zero-indexed element from a list (the row in this case) and then you would have to pattern match to get the specific element from the tuple.
For example, in the following code, getRow fetches the specific row using !!, and then getElem returns the particular tuple element, so that ultimately getElem a 1 1 == 5 for example. You would of course have to add some code to handle out-of-bounds indices:
getRow :: [(Integer, Integer, Integer)] -> Int -> (Integer, Integer, Integer)
getRow matrix row = matrix !! (row :: Int)
getElem :: [(Integer, Integer, Integer)] -> Int -> Int -> Integer
getElem matrix row column
| column == 0 = x
| column == 1 = y
| column == 2 = z
where (x, y, z) = getRow matrix row
hi im trying to make a function in haskell that takes a number a makes a partion of it using lists i.e. for number 4 it would create [[1,1,1,1],[1,1,2],[1,3],[2,2],[4]]. I was thinking of using list comprehension for this where it would create list x and then create further lists using numbers from [1...n] (n being the partition number I would want) where the sum of the list created would be equal to n.
The code I have created so far is-
partions (n:xs) = [[x|x<-[1...n], sum[x]==n]]|xs<-[1..]]
but obiviously it doesnt work, any suggestions?
thanks.
I suggest trying recursion: To obtain the partitions of n, iterate over the numbers i = 1 to n, and recursively generate the partitions of (n-i), the base case being that the only partition of 1 is 1 itself, and the partition of 0 is the empty list.
How about this...
import Data.List (nub, sort)
parts :: Int -> [[Int]]
parts 0 = []
parts n = nub $ map sort $ [n] : [x:xs | x <- [1..n`div`2], xs <- parts(n - x)]
Trying it:
*Main Control.Monad> forM [1..5] (print . parts)
[[1]]
[[2],[1,1]]
[[3],[1,2],[1,1,1]]
[[4],[1,3],[1,1,2],[1,1,1,1],[2,2]]
[[5],[1,4],[1,1,3],[1,1,1,2],[1,1,1,1,1],[1,2,2],[2,3]]
I think it's correct, if not efficient.
I found it helpful to define an auxiliary function, partitionsCap, which does not let any of the items be larger than a given value. Used recursively, it can be used to only produce the monotonically decreasing results you want (i.e. no [1,3,1] when you already have [1,1,3]):
partitions :: Int -> [[Int]]
partitions n = partitionsCap n n
partitionsCap :: Int -> Int -> [[Int]]
partitionsCap cap n
| n < 0 = error "partitions: negative number"
| n == 0 = [[]]
| n > 0 = [i : p | i <- [hi,hi-1..1], p <- partitionsCap i (n-i)]
where hi = min cap n
At the heart of the algorithm is the idea that, when partitioning N, you take i from n down to 1, and prepend i to the partitions of n-i. Simplified:
concat [map (i:) $ partitions (n-i) | i <- [n,n-1..1]]
but wrong:
> partitions 3
[[3],[2,1],[1,2],[1,1,1]]
We want that [1,2] to go away. Hence, we need to cap the partitions we're prepending to so they won't go above i:
concat [map (i:) $ partitionsCap i (n-i) | i <- [hi,hi-1..1]]
where hi = min cap n
Now, to clean it up: that concat and map so close together got my attention. A little background: list comprehensions and the list monad are very closely related, and concatMap is the same as >>= with its arguments flipped, in the list monad. So I wondered: can those concat and map somehow turn into a >>=, and can that >>= somehow sweet-talk its way into the list comprehension?
In this case, the answer is yes :-)
[i : p | i <- [hi,hi-1..1], p <- partitionsCap i (n-i)]
where hi = min cap n
I'm a little rusty with Haskell, but maybe the following code can guide you to find the solution.
parts :: Int -> Int -> [[Int]]
parts 0 p = [[]]
parts x p = [(y:ys) | y <-[p..x], ys <- (parts (x - y) y)]
And then you would have to call parts with x = n, and p = 1.
EDIT
I've fixed the base case when x equals 0 to return a list with a single item, being that item an empty list. Now it works fine :)