Does this break the rules of functional programming?

I’m trying to wrap my head around functional programming, and feel like I might be breaking a few rules here.

def get_published do
  query = from p in Post,
            where: p.published == true

  Repo.all(query)
end

It doesn’t accept any arguments. As I understand it, that should be a dead giveaway that you’re creating side-effects instead of transforming something. I’m not sure how a function like this could be more ‘functional’ though. Is there another way I should be doing this?

2 Likes

You don’t have to assume that schema is Post and don’t use any Repo functions in model I guess:

def get_published(query) do
  from p in query, 
  where: p.published == true
end

Based on this func, use in controller Post.get_published(Post) |> Repo.all()

Remember that queries in Ecto are composable, so you can chain them together

1 Like

Just by using a external database you can assume that your function is impure.
There’s an extent that you can call your code functional in real world applications.

3 Likes

Thanks! I didn’t know queries were composable. That helps thinking about it in a more functional way.

2 Likes

I was wondering about that too. I’ll keep that in mind in the future. Thanks for the feedback!

2 Likes