Created
April 30, 2016 11:31
-
-
Save rundis/8b5a0fd09c3eb348dfc2aa7e862436b4 to your computer and use it in GitHub Desktop.
Reversing a string using a stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Sample where | |
import Stack exposing (..) | |
import String | |
import Html exposing (..) | |
reverseString : String -> String | |
reverseString str = | |
String.split "" str | |
|> Stack.fromList | |
|> Stack.reverse | |
|> Stack.toList | |
|> String.join "" | |
main : Html a | |
main = | |
reverseString "Hello World !" |> Html.text |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Stack exposing (empty, push, pop, reverse, fromList, toList) where | |
type alias Stack a = | |
{ items : List a } | |
empty : Stack a | |
empty = | |
Stack [] | |
push : a -> Stack a -> Stack a | |
push tok stack = | |
{ stack | items = tok :: stack.items } | |
pop : Stack a -> Maybe (a, Stack a) | |
pop stack = | |
case stack.items of | |
(h :: r) -> | |
Just (h, { stack | items = r }) | |
[] -> | |
Nothing | |
reverse : Stack a -> Stack a | |
reverse stack = | |
let | |
listify s = | |
case (pop s) of | |
Nothing -> | |
[] | |
Just (x, r) -> | |
x :: listify r | |
stackify newStack lst = | |
case lst of | |
(h :: r) -> | |
stackify (push h newStack) r | |
[] -> | |
newStack | |
in | |
listify stack |> stackify empty | |
fromList : List a -> Stack a | |
fromList lst = | |
Stack lst | |
toList : Stack a -> List a | |
toList stack = | |
stack.items |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@rundis - would you like to add your code to the Stackoverflow question I posed over there, so I can credit this with the best answer? If you are too busy, I can post it on your behalf.