Skip to content

Instantly share code, notes, and snippets.

@rundis
Created April 30, 2016 11:31
Show Gist options
  • Save rundis/8b5a0fd09c3eb348dfc2aa7e862436b4 to your computer and use it in GitHub Desktop.
Save rundis/8b5a0fd09c3eb348dfc2aa7e862436b4 to your computer and use it in GitHub Desktop.
Reversing a string using a stack
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
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
@kgashok
Copy link

kgashok commented Apr 30, 2016

@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.

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