title: Haskell to find the distance between the two closest points
body: <p>Given a list of points in a two dimensional space, you want to perform a function in
  Haskell to find the distance between the two closest points.
  example:
  Input: project [(1,5), (3,4), (2,8), (-1,2), (-8.6), (7.0), (1.5), (5.5), (4.8), (7.4)]
  Output: 2.0</p>
  
  <p>Assume that the distance between the two farthest points in the list is at most 10000.</p>
  
  <p>Here´s my code:</p>
  
  <pre><code>import Data.List
  import System.Random
  
  sort_ :: Ord a =&gt; [a] -&gt; [a]
  sort_ []    =  []
  sort_ [x]  =  [x]
  sort_ xs   =  merge (sort_ left) (sort_ right)
    where
      (left, right) = splitAt (length xs `div` 2) xs
      merge [] xs = xs
      merge xs [] = xs
      merge (x:xs) (y:ys)=
      if x &lt;= y then 
          x : merge xs (y:ys)
      else  y : merge (x:xs) ys     
  
  project :: [(Float,Float)] -&gt; Float
  project [] = 0
  project (x:xs)=
      if null (xs) then 
          error "The list have only 1 point"
      else head(sort_(dstList(x:xs)))
  
  distance :: (Float,Float)-&gt;(Float,Float) -&gt; Float
  distance (x1,y1) (x2,y2) = sqrt((x1 - x2)^2 + (y1 - y2)^2)
  
  
  dstList :: [(Float,Float)] -&gt; [Float]
  dstList (x:xs)=
      if length xs == 1 then 
          (dstBetween x xs):[]
      else (dstBetween x xs):(dstList xs)
  
  
  dstBetween :: (Float,Float) -&gt; [(Float,Float)] -&gt; Float
  dstBetween pnt (x:xs)=
      if null (xs) then 
          distance pnt x
      else  minimum ((distance pnt ):((dstBetween pnt xs)):[])
  
  {-
  Calling generator to create a file created at random points
  -}
  generator = do
      putStrLn "Enter File Name"
      file &lt;- getLine
      g &lt;- newStdGen
      let pts = take 1000 . unfoldr (Just . (\([a,b],c)-&gt;((a,b),c)) . splitAt 2) 
                  $ randomRs(-1,1) g :: [(Float,Float)]
      writeFile file . show $ pts
  
  {-
  Call the main to read a file and pass it to the function of project
  The function of the project should keep the name 'project' as described 
  in the statement
  -}
  main= do
      putStrLn "Enter filename to read"
      name &lt;- getLine
      file &lt;- readFile name
      putStrLn . show . project $ readA file
  
  readA::String-&gt;[(Float,Float)]
  readA = read
  </code></pre>
  
  <p>I can perform a run of the program as in the example or using the generator as follows:</p>
  
  <p>in haskell interpreter must type "generator", the program will ask for a file name containing a thousand points here. and after the file is generated in the Haskell interpreter must write main, and request a file name, which is the name of the file you create with "generator". </p>
  
  <p>The problem is that for 1000 points randomly generated my program takes a long time, about 3 minutes on a computer with dual core processor. What am I doing wrong? How I can optimize my code to work faster?</p>