Does/Can StringTemplate support Iterable - stringtemplate-4

I would like to iterate over a collection of data stored in an arbitrary data structure. The only interface I have is Iterable. Is this possible with StringTemplate?
<source:{e|e.stuff}>
class Source<HasStuff> implements Iterable<HasStuff> {
// Implementation
}

The current release (4.0.7) supports Iterator, but not Iterable. For details, see the following method, which returns an Iterator for use in the mapping operation.
https://github.com/antlr/stringtemplate4/blob/4.0.7/src/org/stringtemplate/v4/Interpreter.java#L1112-L1132

Related

How to read class/object in Scala documentation

I just learned Scala.
When I read official documentation to look up Array, for example, it has two versions. One is for Class, the other is for Object. I think I know the difference between Class and Object and when I need find methods of Array, I usually go to the Class version. I do not quite know when I need to go to this Object version.It seems when I want to create Multidimensional arrays, I need method(ofDim) in Object version instead of class version. Why?
The identifier Array refers to either the type or its companion object, depending on context.
scala> Array('a', 'b', 'c')
res0: Array[Char] = Array(a, b, c)
res0 is an instance of the Array type. res0 is an object.
scala> Array
res1: Array.type = scala.Array$#1a69136
res1 is the companion object. res1 is an object. It is a singleton, meaning that there are no other objects of its type.
These two objects have different methods on them, because they're very different things.
Instances of the Array type have the methods defined by the class. These are, naturally, the methods that operate on a particular Array instance. For example, the length method returns the length of the array. You need an instance to do this. It wouldn't make sense to write Array.length because that doesn't specify which array you want the length of. But Array('a', 'b', 'c').length is 3.
The companion object has the methods defined by the object. These are the methods that do not require an Array instance. Companion objects will object contain methods that create instances, as is the case for Array. Hence Array.ofDim(2, 2) creates a 2x2 array. That method isn't defined by the class because instances shouldn't have it. For example, it wouldn't make much sense to write Array('a', 'b', 'c').ofDim(2, 2), because the result (an empty 2x2 array) would have nothing to do with the instance that the method was called upon.
As per my understanding, the class defines the actual implementation with methods to operate on the instances (in this case Array - methods like map, count, fold etc.).
The companion object on the other hand provides utility methods for creation (like apply...) (for Array in this case it mostly contains factory methods).
The class methods operate on the class instance data. Like elements of an array for the Array class. The companion object methods usually operate on multiple instances of a class or create one.
The companion objects in Scala play the same role as static members in Java or C#. For example, for Array it mostly contain factory methods. I would not expect to see methods like length or isEmpty on the companion object and on the other hand I would expect to see factory methods on the instance of a class.

Is IEnumerable<object> the proper container for generic data sets?

Using Entity Framework, is IEnumerable the correct container to use to send back a generic data set? I.e. when I do not want to send back a list of the object, but just a generic a result set.
public IEnumerable<object> SelectPlayerFirstAndLastNameList()
{
return (from p in rlpEntities.Players select new { p.PlayerFirstName, p.PlayerLastName });
}
Thanks.
Here is the reference article, which talks about IList(inherits ICollection( and IEnumerable(Base Generic Interface for IQueryable,ICollection,List).
Here are the links which states generics & it's differences & it's usages,
Difference among IEnumerable , IQueryable, ICollection,IList, List
IEnumerable vs. ICollection vs. IQueryable vs. IList
Looking at your linq, it's about specific object & can be extended further in future. IQueryable is right fit for such scenario, as it gives client to iterate/add/remove items.
Check this link out Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?.
It really depends on your scenario, but IEnumerable<> would be used when you need to iterate, and List<> when you need to iterate and modify or sort the data.
IEnunerable<> - http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx
List<> - http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx
You can also use generics, to pass on whatever types you are querying against, like for instance
public IEnumerable<T> SelectPlayerFirstAndLastNameList<T>()
{
return (IEnumerable<T>)(from p in rlpEntities.Players);
}
So you can pass either object, or a known defined type. To call this you would do
var x = SelectPlayerFirstAndLastNameList<YourClassHere>();
I think what you have is correct but decide for yourself whether you should use it.
From MSDN: Anonymous Types in the Remarks section:
Anonymous types are class types that derive directly from object, and
that cannot be cast to any type except object.
and
To pass an anonymous type, or a collection that contains anonymous
types, as an argument to a method, you can declare the parameter as
type object. However, doing this defeats the purpose of strong typing.
If you must store query results or pass them outside the method
boundary, consider using an ordinary named struct or class instead of
an anonymous type.

Creating an arraylist in Scala

I am a teachers assistant for a class that teaches Scala. As an assignment, I want the students to implement an arraylist class.
In java I wrote it like:
public class ArrayList<T> implements List<T>{....}
Is there any equivalent List trait that I should use to implement the arraylist?
The name ArrayList suggests that you should mix-in IndexedSeq. Actually you probably want to get all the goodies that are provided by IndexedSeqLike, i.e.
class ArrayList[A] extends IndexedSeq[A] with IndexedSeqLike[A, ArrayList[A]]
This gets you concrete implementations of head, tail, take, drop, filter, etc. If you also want map, flatMap, etc. (all the methods that take a type parameter) to work properly (return an ArrayList[A]), you also have to provide a type class instance for CanBuildFrom in your companion object, e.g.
def cbf[A, B] = new CanBuildFrom[ArrayList[A], B, ArrayList[B]] {
// TODO Implementation!
}
The scala collection library is very complex. For an overview on the inheritance take a look at these pictures:
scala.collection.immutable: http://www.scala-lang.org/docu/files/collections-api/collections.immutable.png
scala.collection.mutable: http://www.scala-lang.org/docu/files/collections-api/collections.mutable.png
Also the scaladoc gives a good overview about all the classes and traits of the collection library.
Be aware, that in Scala a List is a real list, meaning it is a LinearSeq, in Java a List is more like an IndexedSeq in Scala.
In Scala there are many Interfaces. First, they are separated in mutable and immutable ones. In Java ArrayList is based on an array - thus it is an indexed sequence. In Scala the interface for this is IndexedSeq[A]. Because ArrayList is also mutable, you can choose scala.collection.mutable.IndexedSeq otherwise scala.collection.immutable.IndexedSeq. Instead of mutable.IndexedSeq you can also choose scala.collection.mutable.Buffer, which does not guarantee an access time of O(1).
If you wanna have a more functional approach you can prefer Seq[A] as interface or Iterable[A] if you want to be able to implement more than Sequences.
That would be Seq[T], or maybe IndexedSeq[T] - or even List[T].

Enumerators, iterators, IEnumerable - a bit confused

I've read through the Iterators/Enumerators section of C# 3.0 in a Nutshell several times, but I'm still having a hard time grasping it. From their names, my initial thought is that an Iterator would iterate over a group of Enumerable objects. Am I on the right track? If so, then what about common generic collections, like a List<T>? Does List create/make use of an Iterator during some of its operations? Is T automatically Enumerable? Is there a cast? Does one even have anything to do with the other?
On a somewhat related note, while learning MVC, I've seen code like so:
public Article GetArticle(int id)
{
return _siteDB.Articles.SingleOrDefault(a => a.ArticleID == id);
}
public IEnumerable<Article> GetArticle(string title)
{
return _siteDB.Articles.Where(a => a.Title.StartsWith(title)).AsEnumerable<Article>();
}
What does having a return type of IEnumerable<T> give me?
EDIT: Okay, I think I'm beginning to get it. My confusion remains with Iterators. The book describes them as producers of Enumerators. I don't see where that actually happens with yield return. Does each yield create a new Enumerator?
The type IEnumerable gives you IEnumerable :)
It is an interface defining method GetEnumerator(), which returns IEnumerator. You can call the method as many times as you like and you always obtain new instance of IEnumerator.
The IEnumerator have property Current and methods MoveNext() and Reset() allowing the collection enumeration. The enumeration itself can be done by calling MoveNext() and reading the Current property if previous call of MoveNext() returns true.
Good example of implementation and usage is in documentation: http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx
From their names, my initial thought is that an Iterator would iterate over a group of Enumerable objects. Am I on the right track? If so, then what about common generic collections, like a List? Does List create/make use of an Iterator during some of its operations?
An iterator is a way to implement a method returning an IEnumerable<T> - it's really an implementation detail. Instead of having to create some custom class to enumerate through a collection, you can use an iterator to implement it, and the compiler does the hard work for you.
What does having a return type of IEnumerable give me?
This basically allows you to enumerate over the type. For example, the second method (which I would personally call GetArticles), would allow you to write:
foreach(var article in GetArticle(theTitle))
{
// Do something with article
}
Lets see if I can answer this.
So a List implements IEnumerable, and its not the T that has to implement it, anything in a list can be iterated, using a forech or for loop, for example. If you use a generic list like List, this means that what you have is a list of T where T is the object type defined by you, that means you don't have to cast it, but in the other hand you can only put objects of that same type in that list.
The code you have up there, can mean a series of thing:
1 - Any variable that implements IEnumerable will be able to hold the result of GetArticle,
Ex:
List yourList = GetArticle("test");
Queue myQueue = GetArticle("test");
2 - The actual processing of the query will be delayed. If you call Count for example, after you call the method, thats when it actually get executed/resolved.
3 - Because of number 2, if you are doing that on a DB as the code suggests, then you connection has to remain open till the time where you make use of the list, otherwise you will get an exception.
I think I have answered the questions.

Serializing data using IEnumerable<T> with WebGet

possible duplicate:
Cannot serialize parameter of type ‘System.Linq.Enumerable… ’ when using WCF, LINQ, JSON
Hi,
If my method signiature looks like this, it works fine.
[WebGet]
MyClass[] WebMethod()
If the signiature looks like this
[WebGet]
IEnumerable<T> WebMethod()
I get the following error:
Cannot serialize parameter of type 'X.Y.Z.T+<WebMethod>d__2c' (for operation 'WebMethod', contract 'IService') because it is not the exact type 'System.Collections.Generic.IEnumerable`1[X.Y.Z.T]' in the method signature and is not in the known types collection. In order to serialize the parameter, add the type to the known types collection for the operation using ServiceKnownTypeAttribute.
I have tried adding.
ServiceKnownType(typeof(IEnumerable))
Same error.
Is this a bug in 2010 beta 2, or is this likely to be correct going forward?
Thanks
The iterator types generated by the C# compiler are not serializable and never will be.
If you read this page, you'll see that it wouldn't make sense to serialize the iterator.
You need to return an array.
EDIT: The simplest way to do that is to move your iterator to a seperate method, and change WebMethod to
[WebGet]
MyClass[] WebMethod() { return OtherMethod().ToArray(); }
I've run into the same issue, and in my case it's simply not possible to change my entire object graph from iterator-based IEnumerable to concrete types. I simply cannot afford the memory to convert over to concrete types like List or Array. Additionally, what about the case where I return an IEnumerable of some object that has an IEnumerable property. It is unacceptable that I have to recurse my entire object graph converting all IEnumerables.
I don't see any good reason why the DataContractSerializer can't iterate any IEnumerable type and render its elements to XML in the same manner as any other collection type, even if the IEnumerable doesn't have a concrete backing type.
This is a bug which should be fixed.