Functional programming and non-functional programming

后端 未结 8 1405
情书的邮戳
情书的邮戳 2020-11-28 18:02

In my second year of University we were \"taught\" Haskell, I know almost nothing about it and even less about functional programming.

What is functional programming

8条回答
  •  庸人自扰
    2020-11-28 18:42

    I prefer to use functional programming to save myself repeated work, by making a more abstract version and then using that instead. Let me give an example. In Java, I often find myself creating maps to record structures, and thus writing getOrCreate structures.

    SomeKindOfRecord getOrCreate(T thing) { 
        if(localMap.contains(thing)) { return localMap.get(thing); }
        SomeKindOfRecord record = new SomeKindOfRecord(thing);
        localMap = localMap.put(thing, record);
        return record; 
    }
    

    This happens very often. Now, in a functional language I could write

    RT getOrCreate(T thing, 
                      Function> thingConstructor, 
                      Map> localMap) {
        if(localMap.contains(thing)) { return localMap.get(thing); }
        RT record = thingConstructor(thing);
        localMap = localMap.put(thing,record);
        return record; 
    }
    

    and I would never have to write a new one of these again, I could inherit it. But I could do one better than inheriting, I could say in the constructor of this thing

    getOrCreate = myLib.getOrCreate(*,
                                    SomeKindOfRecord.constructor(), 
                                    localMap);
    

    (where * is a kind of "leave this parameter open" notation, which is a sort of currying)

    and then the local getOrCreate is exactly the same as it would have been if I wrote out the whole thing, in one line, with no inheritance dependencies.

提交回复
热议问题