I have been trying to learn about functional programming, but I still struggle with thinking like a functional programmer. One such hangup is how one would implement index-heavy operations which rely strongly on loops/order-of-execution.
For example, consider the following Java code:
public class Main {
public static void main(String[] args) {
List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7,8,9);
System.out.println("Nums:\t"+ nums);
System.out.println("Prefix:\t"+prefixList(nums));
}
private static List<Integer> prefixList(List<Integer> nums){
List<Integer> prefix = new ArrayList<>(nums);
for(int i = 1; i < prefix.size(); ++i)
prefix.set(i, prefix.get(i) + prefix.get(i-1));
return prefix;
}
}
/*
System.out:
Nums: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Prefix: [1, 3, 6, 10, 15, 21, 28, 36, 45]
*/
Here, in the prefixList
function, the nums list is first cloned, but then there is the iterative operation performed on it, where the value on index i relies on index i-1 (i.e. order of execution is required). Then this value is returned.
What would this look like in a functional language (Haskell, Lisp, etc.)? I have been learning about monads and think they may be relevant here, but my understanding is still not great.
0, a[0], a[a[0]], a[a[a[0]]], ...
requires random access (beyond assuming all the elements are valid indices). In those rare circumstances, we resort to... arrays, e.g.Data.Vector
. Haskell can be used imperatively, when needed -- we just rarely need to do so.List
is implemented as a linked list)? There are functional languages that have value types that are not ADTs, see Swift's Array or Haskell's Vector (mentioned above), while the latter does not support O(1) updating.prefixList()
does not depend on any other data than is passed in its arguments and does not have any effect other than its return value. That's the essence of a pure function. Or course some languages make it easier to write functional code than others, I'd rate Java at about 4.5 out of 10 lambdas.