How do I change a certain value in a matrix in Haskell?

烂漫一生 提交于 2021-02-05 08:48:47

问题


I'm very new to Haskell and haven't fully understood how it works yet. In the following method I would like to change a certain value in a matrix or as it is realized in Haskell, a list of lists.

setEntry :: [[Int]] -> Int -> Int -> Int -> [[Int]]
setEntry x i j aij = 

This is my method so far. I know it's not much but I really don't know how to continue.

The plan is to give it a matrix and then change the value that can be found in the ith line and the jth column to aij.

I'd be very grateful for any kind of help.

Thank you already in advance!


回答1:


First note that there isn't really any need to make this specific to Int-valued matrices: the signature could just as well be

setMatEntry :: [[a]] -> Int -> Int -> a -> [[a]]

Also, instead of just setting it, you might as well modify it, i.e. the new value to put in could depend on the old, right?

modifyMatEntry :: [[a]] -> Int -> Int -> (a -> a) -> [[a]]

With that you could easily implement the original version as

setMatEntry x i j aij = modifyMatEntry x i j (const aij)

or shorter:

setMatEntry x i j = modifyMatEntry x i j . const

The nice thing about approaching it with a modifier than just a constant to be set it that this composes to nested lists of any depth. I.e. there's no reason to right away go to matrices, you might as well first tackle

modifyListEntry :: [a] -> Int -> (a -> a) -> [a]

and then

modifyMatEntry x i j f = modifyListEntry x i
                          (\r -> modifyListEntry r j f)

Here, the outer modifyListEntry works with the [a] -> [a] function that uses the inner modifyListEntry with the a -> a function.

Incidentally, this can actually be made shorter if we turn around the order of arguments: I'd recommend this order

modifyListEntry :: Int -> (a->a) -> [a] -> [a]
modifyMatEntry :: Int -> Int -> (a->a) -> [[a]] -> [[a]]

So, now the only thing that isn't completely trivial is modifyListEntry. But it's clear how, in general, to deal with lists – you're going to have clauses of the form

modifyListEntry i f [] = _
modifyListEntry i f (x:xs) = _

...or possibly also pattern match concrete values for the other parameters. Then you'll need to use recursion. Try to figure that out yourself.



来源:https://stackoverflow.com/questions/65762592/how-do-i-change-a-certain-value-in-a-matrix-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!