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.
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 }