Prolog, find minimum in a list

It is common to use a so-called “lagged argument” to benefit from first-argument indexing: list_min([L|Ls], Min) :- list_min(Ls, L, Min). list_min([], Min, Min). list_min([L|Ls], Min0, Min) :- Min1 is min(L, Min0), list_min(Ls, Min1, Min). This pattern is called a fold (from the left), and foldl/4, which is available in recent SWI versions, lets you write … Read more

Automatically growing lists in Python

Sure it’s possible, you just have to use a subclass of list to do it. class GrowingList(list): def __setitem__(self, index, value): if index >= len(self): self.extend([None]*(index + 1 – len(self))) list.__setitem__(self, index, value) Usage: >>> grow = GrowingList() >>> grow[10] = 4 >>> len(grow) 11 >>> grow [None, None, None, None, None, None, None, None, … Read more

Converting an int array to a String array

int[] nums = {5,1,2,11,3}; //List or Vector Arrays.sort(nums); //Collections.sort() for List,Vector String a=Arrays.toString(nums); //toString the List or Vector String ar[]=a.substring(1,a.length()-1).split(“, “); System.out.println(Arrays.toString(ar)); UPDATE: A shorter version: int[] nums = {-5,1,2,11,3}; Arrays.sort(nums); String[] a=Arrays.toString(nums).split(“[\\[\\]]”)[1].split(“, “); System.out.println(Arrays.toString(a));

readonly keyword does not make a List ReadOnly?

The modifier readonly means that the value cannot be assigned except in the declaration or constructor. It does not mean that the assigned object becomes immutable. If you want your object to be immutable, you must use a type that is immutable. The type ReadOnlyCollection<T> that you mentioned is an example of a immutable collection. … Read more

Serializing a list of Key/Value pairs to XML

KeyValuePair is not serializable, because it has read-only properties. Here is more information(thanks to Thomas Levesque). For changing the generated name use the [XmlType] attribute. Define your own like this: [Serializable] [XmlType(TypeName=”WhateverNameYouLike”)] public struct KeyValuePair<K, V> { public K Key { get; set; } public V Value { get; set; } }

Why isn’t there an operator[] for a std::list?

Retrieving an element by index is an O(n) operation for linked list, which is what std::list is. So it was decided that providing operator[] would be deceptive, since people would be tempted to actively use it, and then you’d see code like: std::list<int> xs; for (int i = 0; i < xs.size(); ++i) { int … Read more