Skip to main content
Tweeted twitter.com/#!/StackMma/status/463518059617984512
Improved formatting
Source Link
m_goldberg
  • 108.1k
  • 16
  • 104
  • 259

I have the following function:

f[lst_List /; MatchQ[lst, SOME PATTERN HERE]] := 
  ({#[[1]] + #[[2]], #[[1]] - #[[2]]} &) /@ lst;

I want to match lists that are ordered pairs of reals: {{0.1, 0.2}, {0.3, 0.4}}, and so on. I tried the following pattern:

MatchQ[{{0.1, 0.2},{0.3, 0.4}}, _List[_List[_Real, _Real]]]

but this returned False. I know that:

MatchQ[{{0.1, 0.2},{0.3, 0.4}}, {__List}]

returns True, but this pattern is not sufficiently specific, since it also matches {{}}, among others.

What is the correct way to construct the pattern I want?

I have the following function:

f[lst_List /; MatchQ[lst, SOME PATTERN HERE]] := ({#[[1]] + #[[2]], #[[1]] - #[[2]]} &) /@ lst;

I want to match lists that are ordered pairs of reals: {{0.1, 0.2}, {0.3, 0.4}}, and so on. I tried the following pattern:

MatchQ[{{0.1, 0.2},{0.3, 0.4}}, _List[_List[_Real, _Real]]]

but this returned False. I know that:

MatchQ[{{0.1, 0.2},{0.3, 0.4}}, {__List}]

returns True, but this pattern is not sufficiently specific, since it also matches {{}}, among others.

What is the correct way to construct the pattern I want?

I have the following function:

f[lst_List /; MatchQ[lst, SOME PATTERN HERE]] := 
  ({#[[1]] + #[[2]], #[[1]] - #[[2]]} &) /@ lst;

I want to match lists that are ordered pairs of reals: {{0.1, 0.2}, {0.3, 0.4}}, and so on. I tried the following pattern:

MatchQ[{{0.1, 0.2},{0.3, 0.4}}, _List[_List[_Real, _Real]]]

but this returned False. I know that:

MatchQ[{{0.1, 0.2},{0.3, 0.4}}, {__List}]

returns True, but this pattern is not sufficiently specific, since it also matches {{}}, among others.

What is the correct way to construct the pattern I want?

Source Link
Shredderroy
  • 5.4k
  • 18
  • 28

What is the correct way to pattern match nested lists?

I have the following function:

f[lst_List /; MatchQ[lst, SOME PATTERN HERE]] := ({#[[1]] + #[[2]], #[[1]] - #[[2]]} &) /@ lst;

I want to match lists that are ordered pairs of reals: {{0.1, 0.2}, {0.3, 0.4}}, and so on. I tried the following pattern:

MatchQ[{{0.1, 0.2},{0.3, 0.4}}, _List[_List[_Real, _Real]]]

but this returned False. I know that:

MatchQ[{{0.1, 0.2},{0.3, 0.4}}, {__List}]

returns True, but this pattern is not sufficiently specific, since it also matches {{}}, among others.

What is the correct way to construct the pattern I want?