私はCodinGameの課題のいくつかを行うことでHaskellを学ぼうと決めました(この質問は初心者レベルのものです)。それらのうちの1つは、任意の2つの値の間の最小の差について整数のリストを検索することを必要とする。尾を再帰的に調べることによるパフォーマンス
readHorses :: Int -> [Int] -> IO [Int]
readHorses n h
| n < 1 = return h
| otherwise = do
l <- getLine
let hn = read l :: Int
readHorses (n - 1) (hn:h)
findMinDiff :: [Int] -> Int -> Int
findMinDiff h m
| (length h) < 2 = m
| (h!!1 - h!!0) < m = findMinDiff (tail h) (h!!1 - h!!0)
| otherwise = findMinDiff (tail h) m
main :: IO()
main = do
hSetBuffering stdout NoBuffering -- DO NOT REMOVE
input_line <- getLine
let n = read input_line :: Int
hPrint stderr n
horses <- readHorses n []
hPrint stderr "Read all horses"
print (findMinDiff (sort horses) 999999999)
return()
大きな入力のためのこのタイムアウト(99999値:
(ns Solution
(:gen-class))
(defn smallest-difference [values]
(let [v (sort values)]
(loop [[h & t] v curr-min 999999]
(if (nil? t) curr-min
(let [dif (- (first t) h)]
(recur t (if (> curr-min dif) dif curr-min)))))))
(defn -main [& args]
(let [horse-strengths (repeatedly (read) #(read))]
(let [answer (smallest-difference horse-strengths)]
(println answer))))
私は次のように、Haskellでは同じソリューションを実装しようとした:私は、以前にこれを行うことにより、Clojureの中でそれを解決してきました)どこClojureソリューションはしません。しかし彼らは私にかなり似ています。
少なくとも、「Read all horses」はタイムアウト前に出力されるため、値を読み込んでリストを構築するのは面倒なことです。
ハスケルバージョンをよりパフォーマンスの高いものにするにはどうすればよいですか?
。私は '[]'と '[_]'の代わりにパターンマッチングを使用したいと思います。 (最後のケースでは、 '(x1:x2:xs)'を使い、部分的な '!!'を避けます - これは速度を向上させませんが、もっと慣用的です) – chi
ありがとう!私は間違いなくこのfindを示すfindMindDiffの実装例に感謝します。 – Orphid