MathGroup Archive 2003

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

Search the Archive

Re: Convert list into function

  • To: mathgroup at smc.vnet.net
  • Subject: [mg41534] Re: [mg41523] Convert list into function
  • From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
  • Date: Mon, 26 May 2003 05:46:15 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

Actually, there are lots of ways to do this.  On reason is that the 
concept of a "function" in Mathematica is very flexible. In one sense a 
function is either a single transformation rule or a set of 
transformation rules attached as DownValues to some symbol. With this 
meaning of a "function" you could use:


L = {1, 2, 3, 4};


f[i_]:=L[[i]]

Now you have just one rule:


DownValues[f]


{HoldPattern[f[i_]] :> L[[i]]}

Alternatively:


Clear[f]


Scan[(f[#1] = #1) & , L]

Now you have a separate rule for each argument:


DownValues[f]


{HoldPattern[f[1]] :> 1, HoldPattern[f[2]] :> 2,
   HoldPattern[f[3]] :> 3, HoldPattern[f[4]] :> 4}

Matheamtica also has another concept of a function (which also has 
several variants), so called "pure functions":

Clear[f]

f=L[[#]]&;

(Now f has no DownValues at all, only an OwnValue).

Of course in all cases f[i] will return i for i=1,2,3,4.

Andrzej Kozlowski
Yokohama, Japan
http://www.mimuw.edu.pl/~akoz/
http://platon.c.u-tokyo.ac.jp/andrzej/


On Saturday, May 24, 2003, at 02:05  pm, rbhatnagar wrote:

> Hi,
>
> A simple question: What is the correct way of converting a list into a
> function?
>
> For instance, lets say I have some list
> L = {1, 2, 3, 4}
>
> and I want a function such that FuncL[1] would return 1, FuncL[2] would
> return 2 and so on.  So what is the syntax for FuncL?
>
> I need the function for some further manipulation in a situation in 
> which
> simply using L[[1]] would not be appropriate.
>
> Thanks,
> R. Bhatnagar
>
>
>
>
>



  • Prev by Date: Re: reading variable names and values from a file
  • Next by Date: Re: Switching x and y axes in a plot
  • Previous by thread: RE: Convert list into function
  • Next by thread: Plots and scaling