0
$\begingroup$

how to give some elements of a list a value that be same always, and cannot change anyway.

a = {1, 0, 1, 1};
SetAttributes[a[[2]], Constant]
SetAttributes::sym: Argument a[[2]] at position 1 is expected to be a symbol. >>

I want to a[[2]] be always 0 , I used SetAttributes but it didn't work.

$\endgroup$
1
  • 1
    $\begingroup$ As far as I know there is no concept of position based constants in Haskell, Mathematica,Lisp, Maxima. In all these lists are mutable. If you think that you will always have more than a specified number of elements, then may be you should use array to force a lower bound on number of elements, because what if you have only one or no element left in your list. May be packages can help you where you can write interface methods for users and do the necessary checking inside private methods. $\endgroup$ – Sejwal Jan 2 '16 at 10:24
3
$\begingroup$

a, the list variable, is a variable, so by definition it can vary. But you could always write your own function as wrapper to do the setting and inside the function, you can check for this.

setMyList[m_List, idx_, value_] := Module[{m0 = m},
  If[idx == 2, m, m0[[idx]] = value; m0]
  ]

and now call it

a = {1, 0, 1, 1};
setMyList[a, 1, 99]
(* {99, 0, 1, 1} *)

But when the index is 2, then it will not change

setMyList[a, 2, 99]
(* {1, 0, 1, 1} *)

The index that is supposed not to be change is hard coded inside the function. But you can change that if you want and pass that as well as an extra parameter.

$\endgroup$
2
  • $\begingroup$ thanks but there should be simple way, I want to use this for boundary condition of a lattice and it will be so tidy if I try it for every lattice sites in boundary. $\endgroup$ – jack cilba Jan 2 '16 at 9:27
  • 1
    $\begingroup$ but there should be simple way, the simple way is to use an if statement. This is what one does in any programming language really. I do not see why it would be different in Mathematica. Trying to play tricks like what you wanted to do is the wrong approach to solve the problem. To get better help, please post a minimal example of the actual problem you are working on. $\endgroup$ – Nasser Jan 2 '16 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.