Skip to content

Instantly share code, notes, and snippets.

@josiah14
Created April 30, 2015 19:55
Show Gist options
  • Save josiah14/c6bc5320eb0e466f50fc to your computer and use it in GitHub Desktop.
Save josiah14/c6bc5320eb0e466f50fc to your computer and use it in GitHub Desktop.
reverse string haskell
-- s is the original string. I recursively call reverse_s on the end of that string until there is nothing left in the string, in
-- which case, I just return the string (providing my edge case that ends the recursion so that I don't end up with infinite recusion).
-- I then prepend each result to the first character of each intermidate string in the recursion until my string has been fully
-- reversed.
reverse_s s = case s of "" -> s
c:cs -> reverse_s cs ++ [c]
-- or you could make it even shorter...
-- foldl is the same as reduce, the part in the parenthesis is a lambda function that takes 2 parameters, an accumulation of the
-- computet result so far, and the current character of the string the calculation is working on.
-- the : operator prepends a list element to an existing list. Since Haskell treats Strings as lists of characters, the accumulation is
-- the reversed string so far, and c is the next char being prepended to the accumulation. When no chars are left, foldl will return
-- the final value of the the last c:accumulation operation, resulting in the fully reversed string.
-- [] is the starting value for foldl, being just an empty list. I could have also used "" here, they are both the same thing in Haskell.
-- I did not need to write a parameter to take the string because I did not need that parameter to define the function. I just say,
-- reverse_s is equivalent to the function I get when I apply my lambda function and my empty list to foldl. Haskell knows that
-- fold1 requires three parameters (the last parameter being the original string that we want to reverse), so it just returns a new
-- function that will take a string as a parameter.
reverse_s' = foldl (\accumulation c -> c:accumulation) []
@josiah14
Copy link
Author

foldl is the same thing as reduce {...} in Ruby

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment