Skip to content

Instantly share code, notes, and snippets.

@thattommyhall
Created January 26, 2024 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thattommyhall/5bb0be5b887a53a74a33e09f4710361b to your computer and use it in GitHub Desktop.
Save thattommyhall/5bb0be5b887a53a74a33e09f4710361b to your computer and use it in GitHub Desktop.
### A Pluto.jl notebook ###
# v0.19.37
using Markdown
using InteractiveUtils
# ╔═╡ 2d681940-0399-401e-910a-d5f181dacec2
eg = :(3x^4 + x^5 - 4x^3 - 2x + 6)
# ╔═╡ e8543900-67a2-4068-b6cb-2840d0d6dfb5
dump(eg)
# ╔═╡ eeb8ca46-1efd-4c1a-947e-6aaf57508c4c
D(i::Int) = 0
# ╔═╡ af29271f-f83a-4dd8-ba96-8337e0c64c0c
D(s::Symbol) = 1
# ╔═╡ b039db96-bc92-11ee-0d01-b3b72281b6ec
function D(e::Expr)
if e.head == :call
f = e.args[1]
args = e.args[2:end]
# If we are +/- terms, D needs to apply to each.
if f == :+ || f == :-
return Expr(:call, f, D.(args)...)
end
# x^n is the same as 1 * x^n
if f == :^
return D(:(1 * $e))
end
# If the expression is a product, it is a * x^n or a * x
if f == :* && length(args) == 2
a, x_exp = args
# ax
if x_exp == :x
return a
end
# a * x^n
if typeof(x_exp) == Expr
if x_exp.head == :call && length(x_exp.args) == 3
f, x, n = x_exp.args
if f == :^ && x == :x && isinteger(n)
return :($(a*n) * x^$(n-1))
end
end
end
end
end
error("Not handled: $(e)")
end
# ╔═╡ 4df3a7cc-af7a-48a6-a146-68f06e438bd1
md"D works for polynomials in standard form"
# ╔═╡ a0cae8ca-7008-4d71-bf18-d5882ee1db2a
eg
# ╔═╡ 0837c131-975b-4d71-91df-c740c4d6ed5d
D(eg)
# ╔═╡ 76e14f69-73e9-458b-8a78-6e8181cb7fc0
md"But some plausible expressions don't work (yet)"
# ╔═╡ 68f12280-3b54-44d8-b826-85a9bd43e94a
D(:(3x^4 + x^5 - 4x^3 - 2 * 2x + 6))
# ╔═╡ Cell order:
# ╠═2d681940-0399-401e-910a-d5f181dacec2
# ╠═e8543900-67a2-4068-b6cb-2840d0d6dfb5
# ╠═eeb8ca46-1efd-4c1a-947e-6aaf57508c4c
# ╠═af29271f-f83a-4dd8-ba96-8337e0c64c0c
# ╠═b039db96-bc92-11ee-0d01-b3b72281b6ec
# ╟─4df3a7cc-af7a-48a6-a146-68f06e438bd1
# ╠═a0cae8ca-7008-4d71-bf18-d5882ee1db2a
# ╠═0837c131-975b-4d71-91df-c740c4d6ed5d
# ╟─76e14f69-73e9-458b-8a78-6e8181cb7fc0
# ╠═68f12280-3b54-44d8-b826-85a9bd43e94a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment