defmodule Dp.Lifo do @moduledoc """ Last-in-first-out @author "hanak@emt.bme.hu" @date "$LastChangedDate: 2024-10-07 07:55:33 +0200 (Mon, 07 Oct 2024) $$" """ @type lifo :: :empty | {lifo, any} # last-in-first-out @spec empty() :: s::lifo # s az üres verem def empty(), do: :empty @spec is_empty(s::lifo) :: b::boolean # b igaz, ha s üres def is_empty(:empty), do: true def is_empty({_s,_x}), do: false @spec push(s::lifo, x::any) :: s_new::lifo # s_new az x-szel megfejelt s verem def push(:empty, x), do: {:empty, x} def push({_s, _x} = s, x), do: {s, x} @spec pop(s::lifo) :: s_new::(lifo | nil) # s\_new az s verem alja, vagy nil, ha s üres def pop(:empty), do: nil def pop({s, _x}), do: s @spec top(s::lifo) :: x::(any | nil) # x az s verem teteje, vagy nil, ha s nem üres # akkor x === nil def top(:empty), do: nil def top({_s, x}), do: x @spec to_list(s::lifo) :: ls::[any] # ls az s verem elemeit tartalmazó lista LIFO sorrendben def to_list(:empty), do: [] def to_list({s, x}), do: [ x | to_list(s) ] def test(1) do # push(push(push(empty, 3), 2), 1); s1 = push(empty(), 1) s2 = push(s1, 2) s3 = push(s2, 3) s3 end def test(2_1) do s = push(push(push(:empty, 1), 2), 3) :io.format("lifo: ~w, top: ~w, pop: ~w~n", [s, top(s), pop(s)]) end def test(2_2) do # wr = fn(s) -> :io.format("lifo: ~w, top: ~w, pop: ~w~n", [s, top(s), pop(s)]) end wr = &(:io_lib.format("lifo: ~w, top: ~w, pop: ~w~n", [&1,top(&1),pop(&1)]) |> to_string) empty() |> push(1) |> push(2) |> push(3) |> wr.() end # karakterláncot megfordít def test(3_1) do lifo = List.foldl(~c"szöveg", :empty, fn(c, a) -> push(a, c) end) to_list(lifo) end # karakterláncot megfordít def test(3_2) do ~c"szöveg" |> List.foldl(:empty, &(push(&2, &1))) |> to_list end # @spec print( lifo) :: none # Kiírja a kimenetre a lifo tartalmát # print(empty) -> # io:format("empty~n"); # print({s,x}) -> # io:format("~p,", [x]), # print(s) end