Skip to content

Instantly share code, notes, and snippets.

@PhyrexTsai
Last active April 23, 2016 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PhyrexTsai/0962a8473f95a3ecee0590b51823f23b to your computer and use it in GitHub Desktop.
Save PhyrexTsai/0962a8473f95a3ecee0590b51823f23b to your computer and use it in GitHub Desktop.
List manipulation.md
quicksort [] = []
quicksort (x:xs) = quicksort small ++ (x : quicksort large)
where small = [y | y <- xs, y <= x]
large = [y | y <- xs, y > x]
isPermutation :: [Int] -> [Int] -> Bool
isPermutation xs ys = (quicksort xs) == (quicksort ys)
main = do
print (isPermutation [1,3,5,7,2,2,2] [2,2,1,3,5,7,2,3])
removeOnce :: Int->[Int]->[Int]
removeOnce x [] = []
removeOnce x lt =
if head lt /= x
then head lt : removeOnce x (tail lt)
else tail lt
isPermutation :: [Int] -> [Int] -> Bool
isPermutation [] [] = True
isPermutation [_] [] = False
isPermutation [] [_] = False
isPermutation lt1 lt2 = do
let lt3 = removeOnce (head lt1) lt2
if lt3 == lt2
then False
else isPermutation (tail lt1) lt3

List manipulation

a. Write a function to determine if the elements of a list form a palindrome, palindrome [Int] -> Bool. For example:

palindrome [ 1, 2, 2, 3, 3] = False
palindrome [ 1, 2, 3, 2, 1] = True
palindrome [3] = True
palindrome [] = True

b. A permutation of a list is another list with the same elements, but in a possibly different order. For example, [1,2,1] is a permutation of [2,1,1], but not of [1,2,2]. Write a function

isPermutation :: [Int] -> [Int] -> Bool

that returns True if its arguments are permutations of each other. For examples:

isPermutation [] [] = True
isPermutation [1,2,1] [2,1,1] = True
isPermutation [1,2,1] [2,1,2] = False
isPermutation [1,2,1] [2,1,1,2] = False

Hint: define a function, removeOnce:: Int->[Int]->[Int], that removes the first occurrence of an element from a list, and use it to implement isPermutation. For examples:

removeOnce 3 [1,3,5,3,4] = [1,5,3,4]
removeOnce 5 [1,2,3,3,4] = [1,2,3,3,4]
removeOnce 3 [] = []
palindrome :: [Int] -> Bool
palindrome xs = xs == reverse xs
main = do
print (palindrome [3,4,5,4,3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment