Reputation:
I need to implement the function is called rufit
Upvotes: 0
Views: 133
Reputation: 1315
First, notice an identity matrix is square, meaning it has n^2 elements, so we need to generate a list of n^2 values. Let's create a list with 1 at the beginning followed by n zeros. Start by replicating zero n times. We can do this with replicate :: Int -> a -> [a]
. Then use cons (:)
to tack a 1 onto the start of the zeros.
1 : replicate n 0
We can use the cycle :: [a] -> [a]
function on the above list to make it infinitely repeat. Due to laziness, it will only compute what is needed. All we really need from the infinite list is the first n^2 elements, so just take :: Int -> [a] -> [a]
the first n^2 elements.
identity n = take (n^2) $ cycle $ 1 : replicate n 0
Upvotes: 1
Reputation: 1382
Try to break the problem into smaller, easier problems.
Maybe start by making a single row, instead of the whole matrix.
To make a row, you need to know the row number and the length n
of the row. So you could have a makeRow
function:
makeRow :: Int -> Int -> [Int]
makeRow n rowNum =
map (\x -> if x == rowNum then 1 else 0) [1..n]
So the position of the 1 in the row depends on the row number.
Now the identity
function is easier. Make a list of rows and then flatten the list:
identity :: Int -> [Int]
identity n =
mconcat $ map (makeRow n) [1..n]
Upvotes: 1
Reputation: 476584
The identity of a number n is a sequence that starts with 1
followed by n-1 sequences of n zeros and one one. So:
n-1 sequences of [0, 0, …, 1]
____________________^_______________________
/ \
indentity n = [1, 0, 0, …, 0, 1, 0, 0, …, 0, 1, …, 0, 0, …, 0, 1]
\___ ____/
v
n times
We can make use of replicate :: Int -> a -> [a]
to repeat an element a given number of times, for example:
Prelude> replicate 4 0
[0,0,0,0]
We thus can make a sequence of n
zeros and one 1
with:
sequence :: Num a => Int -> [a]
sequence n = replicate n 0 ++ [1]
Then the identity function thus should use sequence
as a subexpression. You can make use of concat :: Foldable f => f [a] -> [a]
to concatenate for example a list of lists to a list:
the identity function thus looks like:
identity :: Num a => Int -> [a]
identity n = 1 : …
where you still need to fill in …
.
Upvotes: 1