Re: functions
- To: mathgroup at smc.vnet.net
- Subject: [mg45503] Re: functions
- From: bobhanlon at aol.com (Bob Hanlon)
- Date: Sat, 10 Jan 2004 16:43:24 -0500 (EST)
- References: <bto15f$2gc$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Clear[f,x]; f[x_Rational] := x^2; f[x_Integer] := x^2; f[x_?NumericQ] := 1/x; f /@ {1/2, 3, 5.5, E,x} {1/4, 9, 0.18181818181818182, 1/E, f[x]} Alternatively, Clear[f, x]; f[x_?(Element[#, Rationals]&)] := x^2; f[x_?NumericQ] := 1/x; f /@ {1/2, 3, 5.5, E,x} {1/4, 9, 0.18181818181818182, 1/E, f[x]} However, if you also want to handle Symbols that have been explicitly declared as either Rational or Integer Clear[f,x,n]; f[x_?(Element[#, Rationals]|| Element[#, Integers]&)] := x^2; f[x_?NumericQ] := 1/x; x /: Element[x, Rationals] = True; n /: Element[n, Integers] = True; f /@ {1/2, 3, 5.5, E,x, n,y} {1/4, 9, 0.18181818181818182, 1/E, x^2, n^2, f[y]} For the second example, Clear[f,n]; f[n_?OddQ] := 1/n; f[n_?EvenQ] := n^2; n /: EvenQ[n] = True; f /@ {-6, -3,0,3,6,5.5, n,x} {36, -(1/3), 0, 1/3, 36, f[5.5], n^2, f[x]} Bob Hanlon In article <bto15f$2gc$1 at smc.vnet.net>, lorenzo.keegan at handbag.com wrote: << How do write expressions in Mathematica for functions and sequences such as the following: f(x) = {1/x, x is irrational {x^2, x rational and f(n) = 1/n, n odd n^2, n even