MathGroup Archive 2007

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: a beginner's question

On 6/16/07 at 3:31 AM, tunganhtr at (tung tran) wrote:

>I am a beginner in Mathematica and in programming. I read the book
>"An Introduction to Programming with Mathematica". Page 155:

>FindSubsequence[lis_List, subseq_List] := Module[{p}, p =
>Partition[lis, Length[subseq], 1]; Position[p, Flatten[{___,
>subseq, ___}]]]

>I want to know more about the role of Module function and " ; "  in
>these lines. I have read documentation about Module function but it
>doesn't help me much in understanding this line of code. Thanks for
>helping me !

Module is being used to declare a local variable, p that is gets
assigned the result from Partition. The ; is used to create a
compound expression. It effectively terminates one statement
before beginning another. If the code were written

=46indSubsequence[lis_List, subseq_List] :=
     p = Partition[lis, Length[subseq], 1]
     Position[p, Flatten[{___, subseq, ___}]]]

that is omitting the ; Mathematica would attempt to multiply
Partition[...] by Position[...] which is clearly not meaningful.
Note, this would actually generate a recursion error since p
would appear on both sides of the "=".

Other ways to write this function would be to define p at the
same time it is declared, i.e.,

=46indSubsequence[lis_List, subseq_List] :=
   Module[{p = Partition[lis, Length[subseq], 1]},
     Position[p, Flatten[{___, subseq, ___}]]]

which eliminates the need for the ;

or you could dispense with Module altogether by writing this
function as:

=46indSubsequence[lis_List, subseq_List] :=
     Position[Partition[lis, Length[subseq], 1], Flatten[{___,
subseq, ___}]]

Although functionally these are all the same, their readability
is not the same and likely the ease of maintaining the code at
some later time will be different
To reply via email subtract one hundred and four

  • Prev by Date: is there a better way to iterate this?
  • Next by Date: more gripe about the new documentation center (DC) in Mathematica 6
  • Previous by thread: Re: a beginner's question
  • Next by thread: Re: a beginner's question