Longest string challenge: Difference between revisions

Added a Haskell solution.
m (underscored a restriction that appeared to be ignored by a majority of entries/implementations.)
(Added a Haskell solution.)
Line 963:
ddd
ccc</pre>
 
=={{header|Haskell}}==
 
Even though lists of strings were disallowed in the rules, I have used them instead of a file handle, mainly to keep my functions pure, and to avoid the hassle of using the IO monad for something more trivial without it.
 
Another use of lists in the code is for Strings, which are lists of Chars in Haskell by default, which made it easy to compare them by length.
 
No operators were used except for string/list concatenation.
 
<lang Haskell>
module Main where
 
import System.Environment
 
cmp :: String -> String -> Ordering
cmp [] [] = EQ
cmp [] (_:_) = LT
cmp (_:_) [] = GT
cmp (_:xs) (_:ys) = cmp xs ys
 
longest :: String -> String
longest = longest' "" "" . lines
where
longest' acc l [] = acc
longest' [] l (x:xs) = longest' x x xs
longest' acc l (x:xs) = case cmp l x of
LT -> longest' x x xs
EQ -> longest' (acc ++ '\n':x) l xs
GT -> longest' acc l xs
 
main :: IO ()
main = do
(file:_) <- getArgs
contents <- readFile file
putStrLn $ longest contents
</lang>
 
=={{header|Icon}} and {{header|Unicon}}==
Anonymous user