Haskell: Creating an isEqual function for a list

时间:2016-04-04 17:11:01

标签: haskell

I want to create an isEqual function to compare the length of each string in a list. If each String is of equal size e.g. ["that", "there", "9999", " 1 #"]

return True if all strings are equal length ELSE return False.

I'm looking for a way that requires the least amount of code and run time.

3 个答案:

答案 0 :(得分:2)

probably easier to write it recursively

isEq [] = True
isEq [x] = True
isEq (x:y:xs) = x==y && isEq (y:xs)

so short circuits with the first unequal size.

答案 1 :(得分:0)

You can try

minimumBy length == maximumBy length

(untested, and doesn't work for empty lists)

答案 2 :(得分:0)

There is always the one liner....

(== 1) . length . nub

You will need to import Data.List. This will perform less well than pattern matching (barely so for lists smaller than 100), but it is easy to read, and probably fits the criteria "least amount of code".