The Artima Developer Community
Sponsored Link

Scala Buzz
pairMap revisited

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Jeff Heon

Posts: 40
Nickname: jfheon
Registered: Feb, 2005

Jeff Heon is software developer who has worked mainly with OO languages.
pairMap revisited Posted: Jan 24, 2009 9:14 AM
Reply to this message Reply

This post originated from an RSS feed registered with Scala Buzz by Jeff Heon.
Original Post: pairMap revisited
Feed Title: The Careful Programmer
Feed URL: http://thecarefulprogrammer.blogspot.com/feeds/posts/default
Feed Description: A (starting) collection of my musings about programming. I'll brush more often on Scala related topics since I am currently learning it.
Latest Scala Buzz Posts
Latest Scala Buzz Posts by Jeff Heon
Latest Posts From The Careful Programmer

Advertisement
A while ago, I needed a list function similar to a fold, but I wanted to operate always with the current and previous element instead of accumulating a result to operate with the current element (and return a list of the results of each pair operation)

I originally wrote it more or less like this:

def pairMap[A,B](previous:A, aList:List[A], f: (A, A) => B): List[B] = aList match {
    case Nil => Nil
    case head :: tail => f(previous, head)::pairMap(head, tail, f)
}

I was using it in the context of getting a list of gaps between the numbers of a list:

def getGapList(aList: List[int]) = pairMap(aList.head, aList.tail, (a:Int, b:Int)=>(b - a))

Usage example:

val list = List(2, 5, 9)
list: List[Int] = List(2, 5, 9)

getGapList(list)
res1: List[Int] = List(3, 4)

The other day, reminiscing about the Fibonacci example in "A Gentle Introduction to Haskell Version 98", a different implementation occurred to me. Unsurprisingly, it involves zipping a list with itself 8)

Thinking about folds, I thought I might as well put an initial value.

def pairMapWithInitial[A,B](initial:A, aList:List[A], f: (Tuple2[A, A]) => B):List[B] = {
    initial::aList zip aList map f
}

def getGapListWithInitial(initial:int, aList:List[int]) = pairMapWithInitial(initial, aList, (a:Tuple2[Int,Int])=>(a._2 - a._1))

Usage example:

getGapListWithInitial(list.head, list.tail)
res2: List[Int] = List(3, 4)

getGapListWithInitial(0, list)
res3: List[Int] = List(2, 3, 4)

Because it's clearer to me, I still prefer the first version with "match", but it was a nice exercise to explore the zip version.

Read: pairMap revisited

Topic: Refactoring Scala Actors Previous Topic   Next Topic Topic: Scala Plugin 0.15.1 for NetBeans Released

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use