Arc Forumnew | comments | leaders | submit | Tichy's commentslogin
1 point by Tichy 6119 days ago | link | parent | on: Clarification about Character Sets

What is the usage scenario for that? I have never written such a code (incrementing values in hashtables) - maybe it is more common in LISP?

-----

1 point by bOR_ 6119 days ago | link

Happens when you want to categorize the frequency of items in a list, and I've been doing that all the time (categorizing gene frequencies in an agent-based model).

In ruby I'd extend the array class with this code

  class Array
    def categorize
      hash = Hash.new(0)
      self.each {|item| hash[item] += 1}
      return hash
    end
  end
although the other day I saw someone achieve the same thing using a hack on inject (the `; hash' part is only there because inject demands that, the work is done earlier.)

  array.inject(Hash.new(0)) {|hash,key| hash[key] += 1 ; hash}
Noticing that lisp / arc is more concise indeed. I'll have fun learning it.

-----

1 point by smallpaul 6116 days ago | link

Why would you extend rather than subclass the Array class? It kind of confirms all of my worst fears about Ruby's too-easy class reopening. (what happens when someone else defines an Array method called "categorize" for a totally unrelated purposes?)

I think that the Python syntax for this is

h[x] = h.get(x, 0) + 1

It isn't quite as concise as the Common Lisp but more so than Arc. I'd be curious to see what the Common Lisp looks like if you are doing something more complicated than an in-place increment. E.g. the equivalent of:

h[x] = h.get(x, 1) * 2

-----

2 points by bOR_ 6113 days ago | link

I'm a phd, working alone on projects, and the scripts I write a generally < 300 lines + 6 functions from a library I wrote. The agent-based models i write are ~ 200 lines, no libraries.

For me there's not much risk in redefining things.

-----

1 point by jsg 6115 days ago | link

(setf (gethash x h) (* (gethash x h 1) 2))

-----

1 point by ijoshua 6116 days ago | link

A hashtable containing integer values is a common implementation for the collection data structure known as a Bag or Counted Set. The value indicates how many instances of the key appear in the collection. Incrementing the value would be equivalent to adding a member instance. Giving a zero default is a shortcut to avoid having to check for membership.

-----