2 ms·
I think there are cases where the functional style is more legible, but also cases where imperative style is more legible. I really think the imperative style i
by trealira 3y ago
I think there are cases where the functional style is more legible, but also cases where imperative style is more legible. I really think the imperative style is more legible in this particular case.
This is why Haskell and OCaml allow imperative constructs when they're more legible. I'll take an example from Learn You a Haskell[1]. In Haskell, one can implement a quick and dirty stack like this:
type Stack = [Int]
-- Throws exception on empty list/Stack
pop :: Stack -> (Int, Stack)
pop (x:xs) = (x, xs)
push :: Int -> Stack -> ((), Stack)
push a xs = ((), a:xs)
You can then write a function to push 3 onto the stack, then pop two items off the stack, returning the second popped item—this is equivalent to just popping an item from the stack and returning it, but the point is to show off the stack manipulation.
stackManip :: Stack -> (Int, Stack)
stackManip stack = let
((), newStack1) = push 3 stack
(_, newStack2) = pop newStack1
in pop newStack2
But using the state monad, it is more legibly written like this:
import Control.Monad.State
stackManip :: State Stack Int
stackManip = do
push 3
_ <- pop
pop
[1]: http://learnyouahaskell.com/for-a-few-monads-more http://learnyouahaskell.com/for-a-few-monads-more
- hajile 3y agoIn this case, imperative with spread would be just as slow and no more readable. The real issue is that this should have been wired up with an iterator. At that point, you aren’t using a for loop and your iterator might actually be faster with property tail calls.