如何更改Haskell矩阵中的某个值? [英] How do I change a certain value in a matrix in Haskell?

查看:33
本文介绍了如何更改Haskell矩阵中的某个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Haskell还是陌生的,还没有完全了解它是如何工作的.在下面的方法中,我想更改矩阵中的某个值或在Haskell中实现的列表列表.

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.

计划是给它一个矩阵,然后将第i行和第j列中可以找到的值更改为aij.

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.

已经谢谢你了!

推荐答案

首先请注意,实际上并不需要针对特定​​于 Int 值的矩阵进行设置:签名也可以是

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)

或更短:

setMatEntry x i j = modifyMatEntry x i j . const

使用修饰符进行处理的好处在于,它不仅仅是要设置为常量的常量,它可以组成任何深度的嵌套列表.IE.没有理由马上去矩阵,您最好还是先解决

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]

然后

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

在这里,外部的 modifyListEntry [a]->一起使用.[a] 函数,将内部 modifyListEntry a->一起使用一个函数.

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]]

因此,现在唯一不完全琐碎的是 modifyListEntry .但是很明显,通常来说,如何处理列表–您将拥有以下形式的子句

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.

这篇关于如何更改Haskell矩阵中的某个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆