Skip to content

Instantly share code, notes, and snippets.

@kgashok
Forked from rundis/Sample.elm
Created April 30, 2016 17:30
Show Gist options
  • Save kgashok/66bc119e232a8e018d37dbf94edb95ee to your computer and use it in GitHub Desktop.
Save kgashok/66bc119e232a8e018d37dbf94edb95ee 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment