-
-
Save kgashok/66bc119e232a8e018d37dbf94edb95ee 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