您将如何使用函数编程编写此代码

时间:2017-08-19 01:38:55

标签: oop functional-programming

我正在学习面向对象和函数式编程。我发现这个非常好的简短例子(如果你知道更好的例子,请建议)在youtube上解释10分钟的OOP,是的! https://www.youtube.com/watch?v=4c4nP7GLL1c

现在,我想学习如何以函数方式编写此代码 - 具有不变性,递归无循环等。

DEMO.PHP
<?php
Include_once(“player.php”);

$p1 = new player();
$p1->name = “Brutus”;
$p1->type = “Warrior”;
$p1->hitpoints = 100;

$p2 = new player();
$p2->name = “Mysterio”;
$p2->type = “Sorcerer”;
$p2->hitpoints = 100;

$p1->meleeAttack($p2);
$p2->meleeAttack($p1);

Echo “<h1> Fight Results</h1>”;
Echo “<h2>.$p1->name.” now has “.$p1->hitpoints.” hit points</h2>”;
Echo “<h2>.$p2->name.” now has “.$p2->hitpoints.” hit points</h2>”;
?>


PLAYER.PHP
<?php
Class player {

    public $name;
    public $type;
    public $hitpoints;
    public function meleeAttack($target){
        $current_hp = $target->hitpoints;   // hp is for hitpoints
        $damage = rand(10,20);
        if($this->type == “Warrior”) {      // condition logic
            $damage += 10;
        }
        $target->hitpoints = $current_hp - $damage;
    }
}

?>

干杯, 附:我知道,PHP不是函数式编程的首选语言,不需要提醒它:)

1 个答案:

答案 0 :(得分:4)

我将解释如何使用Haskell进行函数式编程,因为我不了解PHP:

import System.Random (randomRIO)

-- Data Declarations

data Class = Warrior | Sorcerer deriving Eq

data Player = Player { name      :: String
                     , archetype :: Class
                     , hitpoints :: Int
                     }

-- Example Data

p1 :: Player
p1 = Player "Brutus" Warrior 100

p2 :: Player
p2 = Player "Mysterio" Sorcerer 100

-- Code Section

meleeAttack :: Player -> Player -> IO Player
source `meleeAttack` target = do
    damage <- randomRIO (10, 20)
    let bonus = if archetype source == Warrior then 10 else 0
    let newHP = hitpoints target - damage - bonus
    return target { hitpoints = newHP }

-- Main Function

main :: IO ()
main = do
    p2 <- p1 `meleeAttack` p2
    p1 <- p2 `meleeAttack` p1
    putStrLn "Fight Results"
    putStrLn (name p1 ++ " now has " ++ show (hitpoints p1) ++ " hitpoints")
    putStrLn (name p2 ++ " now has " ++ show (hitpoints p2) ++ " hitpoints")

好吧,面向对象编程和函数式编程之间最大的区别之一就是代码和数据的分离:

  1. 在面向对象的编程中,代码和数据不是分开的。看看你自己的Player课程。它有三个公共字段和一个在这些字段上运行的公共方法。
  2. 在函数式编程中,代码和数据是分开的。我们的数据声明是在程序的开头,随后是对该数据进行操作的函数。
  3. 另一个重大差异是可变性。在面向对象的编程中,对象通常是可变的。因此,方法通常会修改现有对象。在功能编程中,突变被认为是坏的。因此,函数通常不会修改任何东西。相反,他们返回他们正在操纵的任何数据的更新副本。

    例如,考虑meleeAttack函数。它需要两个输入sourcetarget,它们都是Player数据。输出也是Player数据。它是已更新的target。原始target未经修改。

    无论如何,如果你想学习函数式编程,那么你应该阅读Learn You A Haskell