3

How can we use a conditional or pattern test to make our function accept any symbols as input except for lists?

Mr.Wizard
  • 24,179
  • 5
  • 44
  • 125
Sunday
  • 87
  • 2
  • 8
  • I'm not sure what you're trying to accomplish. Can you include an example of what you'd like to avoid? – rcollyer Apr 02 '11 at 01:11
  • ohkaay! ill try again. How can we "Use a conditional or pattern test to make our function accept any symbols as input except for lists." – Sunday Apr 02 '11 at 01:51

1 Answers1

8

Use Except:

f[x : Except[_List]] := doSomethingTo[x]

expr /. x : Except[_List] :> doSomethingElseTo[x]

You can combine that with Alternatives (infix operator |) to exclude several things:

g[x : Except[_List | _Rational]] := etc[x]

Edit: Consolidating answers from the comments too:

ListQ[expr] will return True if expr is a list (has head List) and False otherwise. MatchQ[expr, _List] and Head[expr]===List are equivalent ways to accomplish the same thing.

Michael Pilat
  • 6,480
  • 27
  • 30
  • is there an easier approach for this ... i'm trying to use if condition here's my approach " checklogderivate [expr_] := If[ expr = _List, "Invalid input form", D[expr , x]*(1/expr), "Invalid input notation"]; "example: checklogderivate[{x^3 y^2, xy}]" – Sunday Apr 02 '11 at 02:34
  • 1
    @Sunday: `expr = _List` should either be a `MatchQ[expr, _List]` or `Head[expr]===List`... – Simon Apr 02 '11 at 02:56
  • 1
    @Simon, @Sunday: there is also `ListQ[expr]` which returns `True` if `expr` is a list and `False` otherwise. TMTOWTDI =) – Michael Pilat Apr 02 '11 at 03:13
  • I decided to do it this way " If[ Length[expr] != 1,"invalid", do something specified, 0]" – Sunday Apr 02 '11 at 03:26
  • 3
    @Sunday: Be careful with that, for example `Length[f[x]]` is `1` too. – Michael Pilat Apr 02 '11 at 03:27
  • 2
    And, e.g. `Length[3]` is `0`, so I don't see how that accomplished what you asked in the first place =) – Michael Pilat Apr 02 '11 at 03:30
  • @Michael +1 Important observation about Length being unsuitable for determining whether one is dealing with a list. – DavidC Apr 02 '11 at 04:56
  • How about this one...... checklogderivate [expr_] := If[ Length[expr] != 1, "Invalid input form", D[expr , x]*(1/expr), "Invalid input notation"]; checklogderivate[{3}] checklogderivate[{x^3 y^2, xy}] – Sunday Apr 05 '11 at 01:12
  • That works, but it wasn't what you asked about originally. You asked how to make sure a function argument isn't a list. `{3}`, for example, is still a list, and of length 1. `{3}` is really `List[3]`, the braces are syntactic sugar for the full expression. Everything is an expression in Mathematica. A function that takes one argument `x` could also be defined as `f[x_] := x+1`. A function that takes two arguments could be defined as `f[x_, y_] := x+y`. However, `f[x_]` would still accept a `List` as its one argument, because the pattern `_` will match anything. – Michael Pilat Apr 05 '11 at 03:14