Created
January 23, 2016 14:10
-
-
Save cesare/d094370a07c3ee9c5839 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.List ((\\)) | |
import qualified Data.Map as Map | |
prune :: Ord k => Map.Map k k -> Map.Map k k | |
prune m = _prune m orphans | |
where | |
_prune m [] = m | |
_prune m os = prune $ foldl (flip Map.delete) m os | |
orphans = (Map.keys m) \\ (Map.elems m) | |
{- | |
import qualified Data.Map.Lazy as Map | |
let sample = Map.fromList [(1,3), (2,1), (3,1), (4,5), (5,5), (6,4), (7,6)] | |
prune sample | |
-} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Map | |
def initialize(pairs) | |
@relations = pairs.each_with_object({}) do |(a,b), rel| | |
rel[a] = b | |
end | |
end | |
def map(a) | |
@relations[a] | |
end | |
def prune | |
os = orphans | |
return self if os.empty? | |
self.class.new(@relations.reject{|x,_| os.include? x }).prune | |
end | |
def orphans | |
@relations.keys - @relations.values | |
end | |
def one_to_one? | |
duplicates.empty? | |
end | |
def duplicates | |
reverse.select {|b, as| as.count > 1 } | |
end | |
def reverse | |
@relations.map{|a,b| [b,a]}.each_with_object({}) {|(b,a), h| (h[b] ||= []) << a } | |
end | |
end | |
map = Map.new [[1,3], [2,1], [3,1], [4,5], [5,5], [6,4], [7,6]] | |
map.prune | |
map.prune.one_to_one? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment