Gavin
Gavin

Reputation: 4698

Modify an argument in a pure function

I am aware that I should not do this

I am asking for dirty hacks to do something nasty

Goal

I wish to modify an argument in a pure function.

Thus achieving effect of pass by reference.

Illustration

For example, I have got the following function.

fn :: a -> [a] -> Bool
fn a as = elem a as

I wish to modify the arguments passed in. Such as the list as.

as' = [1, 2, 3, 4]
pointTo as as'

Upvotes: 1

Views: 546

Answers (1)

leftaroundabout
leftaroundabout

Reputation: 120741

It is a common misconception that Haskell just deliberately prevents you from doing stuff it deems unsafe, though most other languages allow it. That's the case, for instance, with C++' const modifiers: while they are a valuable guarantee that something which is supposed to stay constant isn't messed with by mistake, it's generally assumed that the overall compiled result doesn't really change when using them; you still get basically impure functions, implemented as some assembler instructions over a stack memory frame.

What's already less known is that even in C++, these const modifiers allow the compiler to apply certain optimisations that can completely break the results when the references are modified (as possible with const_cast – which in Haskell would have at least “unsafe” in its name!); only the mutable keyword gives the guarantee that hidden modifications don't mess up the sematics you'd expect.

In Haskell, the same general issue applies, but much stronger. A Haskell function is not a bunch of assembler instructions operating on a stack frame and memory locations pointed to from the stack. Sometimes the compiler may actually generate something like that, but in general the standard is very careful not to suggest any particular implementation details. So actually, functions may get inlined, stream-fused, rule-replaced etc. to something where it totally wouldn't make sense to even think about “modifying the arguments”, because perhaps the arguments never even exist as such. The thing that Haskell guarantees is that, in a much higher-level sense, the semantics are preserved; the semantics of how you'd think about a function mathematically. In mathematics, it also doesn't make sense at all, conceptually, to talk about “modified arguments”.

Upvotes: 5

Related Questions