Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Issue #44 - Split and SplitBy #47

Merged
merged 3 commits into from
Sep 26, 2012
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
partially add SplitBy fixes #44
  • Loading branch information
sn6uv committed Sep 26, 2012
commit 5eb56a44bd817e025fd501e71f2f81fa732d8ffd
45 changes: 44 additions & 1 deletion mathics/builtin/lists.py
Original file line number Diff line number Diff line change
Expand Up @@ -979,7 +979,50 @@ def apply(self, mlist, test, evaluation):
result.append([leaf])

return Expression(mlist.head, *[Expression('List', *l) for l in result])


class SplitBy(Builtin):
"""
<dl>
<dt>'Split[$list$, $f$]'
<dd>splits $list$ into collections of consecutive elements that give the same result when $f$ is applied.
<dl>

>> SplitBy[Range[1, 3, 1/3], Round]
= {{1, 4 / 3}, {5 / 3, 2, 7 / 3}, {8 / 3, 3}}
"""

rules = {
'SplitBy[list_]': 'SplitBy[list, Identity]',
}

messages = {
'normal': 'Nonatomic expression expected at position `1` in `2`.',
}

def apply(self, mlist, f, evaluation):
'SplitBy[mlist_, f_]'

expr = Expression('Split', mlist, f)

if mlist.is_atom():
evaluation.message('Select', 'normal', 1, expr)
return

if Expression('ListQ', f).evaluate(evaluation) == Symbol('True'): #TODO
raise NotImplementedError

result = [[mlist.leaves[0]]]
prev = Expression(f, mlist.leaves[0]).evaluate(evaluation)
for leaf in mlist.leaves[1:]:
curr = Expression(f, leaf).evaluate(evaluation)
if curr == prev:
result[-1].append(leaf)
else:
result.append([leaf])
prev = curr

return Expression(mlist.head, *[Expression('List', *l) for l in result])

class Cases(Builtin):
rules = {
'Cases[list_, pattern_]': 'Select[list, MatchQ[#, pattern]&]',
Expand Down