title: Scala: recursively modify lists of elements/lists
body: <p>I was hoping someone could provide me with some basic code help in Scala. I've written some demo code in Python.</p>
  
  <p>Consider a list of elements, where an element can hold either an integer or a list of other elements. I'd  like to recursively examine this structure and modify it while keeping the overall structure.</p>
  
  <p>To represent this in python, I've made each 'element' a dictionary with one key ('i' for item). The value corresponding to that key is either an int, or a list of similar dicts. Thus, </p>
  
  <pre><code>lst = [{'i': 1}, {'i': 2}, {'i': [{'i': 5}, {'i': 6}]}, {'i': 3}]
  
  def recurse(x):
    if isinstance(x, list):
      return [recurse(a) for a in x]
    else:
      if isinstance(x['i'], list):
        return dict(i=[recurse(a) for a in x['i']])
      else:
        return dict(i=(x['i'] + 1))
  
  print "Input:"
  for i in lst:
      print i
  print "\nResult:\n%s" % recurse(lst)
  
  &gt;&gt;&gt;
  Input:
  {'i': 1}
  {'i': 2}
  {'i': [{'i': 5}, {'i': 6}]}
  {'i': 3}
  
  Result:    
  [{'i': 2}, {'i': 3}, {'i': [{'i': 6}, {'i': 7}]}, {'i': 4}]
  </code></pre>
  
  <p>I understand it's a bit of a weird way to go about doing things, but the data I have been provided is structured like that. I think my issue is that python lets you return different types from the same function, while I don't believe Scala does.</p>
  
  <p>Also for the record, the Scala elements are represented as Elem(4), or Elem(List(Elem(3)..., so I assume pattern matching can come into it somewhat.</p>