Skip to content

Instantly share code, notes, and snippets.

@ppurang
Created December 4, 2011 11:27
Show Gist options
  • Save ppurang/1429947 to your computer and use it in GitHub Desktop.
Save ppurang/1429947 to your computer and use it in GitHub Desktop.
map a list of functions to a single value
-- import Control.Monad (ap)
type Pos = (Int, Int)
type Direction = Pos -> Pos
direction :: Pos -> [Direction] -> [Pos]
direction p [] = []
direction p (x:xs) = x p : direction p xs
-- another way
-- direction p ds = ap ds [p]
north (x,y) = (x-1,y)
south (x,y) = (x+1,y)
east (x,y) = (x,y+1)
west (x,y) = (x,y-1)
northeast (x,y) = (x-1,y+1)
southeast (x,y) = (x+1,y+1)
northwest (x,y) = (x-1,y-1)
southwest (x,y) = (x+1,y-1)
directions :: [Direction]
directions = [north, south, east, west, northeast, northwest, southeast, southwest]
-- application
-- direction (1,1) directions
-- [(0,1),(2,1),(1,2),(1,0),(0,2),(0,0),(2,2),(2,0)]
/*
The following can't be used in the REPL so do this:
> scalac directions.scala
> scala -cp directions
scala> import directions._
scala> directions (1,1)
res1: List[(Int, Int)] = List((0,1), (0,2), (1,2), (2,2), (2,1), (2,0), (1,0), (0,0))
*/
package object directions { //allows defining some type aliases
type Pos = (Int, Int)
type Direction = (Int,Int) => (Int,Int)
//different roads to rome
val north : Direction = (x,y) => (x-1,y)
val northeast = (x:Int,y:Int) => (x-1,y+1)
//choose one of the roads and minimize the pain
val east : Direction = (x,y) => (x,y+1)
val southeast : Direction = (x,y) => (x+1, y+1)
val south : Direction = (x,y) => (x+1,y)
val southwest : Direction = (x,y) => (x+1,y-1)
val west : Direction = (x,y)=>(x,y-1)
val northwest : Direction = (x,y)=>(x-1,y-1)
val alldirections = List(north.tupled, northeast.tupled, east.tupled, southeast.tupled, south.tupled, southwest.tupled, west.tupled, northwest.tupled)
//or alternative list creation
//val directions = north :: northeast :: east ...... :: Nil
def directions(p: Pos) = for(d <- alldirections) yield d(p)
//you say even more compact
def directionsTwo(p: Pos) = alldirections map (_(p))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment