forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMap.cs
More file actions
72 lines (58 loc) · 2.39 KB
/
Map.cs
File metadata and controls
72 lines (58 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections;
using System.Linq;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting.Runtime;
namespace IronPython.Runtime {
[PythonType("map")]
[Documentation(@"map(func, *iterables) -> map object
Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.")]
public class Map : IEnumerator {
private readonly CodeContext _context;
private readonly object? _func;
private readonly IEnumerator[] _enumerators;
public Map(CodeContext context, object? func, [NotNone] params object[] iterables) {
if (iterables.Length == 0) {
throw PythonOps.TypeError("map() must have at least two arguments.");
}
_enumerators = new IEnumerator[iterables.Length];
for (var i = 0; i < iterables.Length; i++) {
var iter = iterables[i];
if (!PythonOps.TryGetEnumerator(context, iter, out var enumerator)) {
throw PythonOps.TypeErrorForNotIterable(iter);
}
_enumerators[i] = enumerator;
}
_context = context;
_func = func;
}
[PythonHidden]
public object? Current { get; private set; }
[PythonHidden]
public bool MoveNext() {
if (_enumerators.Length > 0 && _enumerators.All(x => x.MoveNext())) {
Current = PythonOps.CallWithContext(_context, _func, _enumerators.Select(x => x.Current).ToArray());
return true;
}
Current = default;
return false;
}
[PythonHidden]
public void Reset() { throw new NotSupportedException(); }
public PythonTuple __reduce__() {
var args = new object?[_enumerators.Length + 1];
args[0] = _func;
Array.Copy(_enumerators, 0, args, 1, _enumerators.Length);
return PythonTuple.MakeTuple(
DynamicHelpers.GetPythonTypeFromType(typeof(Map)),
PythonTuple.MakeTuple(args)
);
}
}
}