LoginSignup
0
1

More than 5 years have passed since last update.

C#/Python手遊び(lambda式とかのミニマムコード)

Last updated at Posted at 2019-03-09

この記事、何?

ちょっと前に初めて書いてみたlambda式とか。
旧世代言語との付き合いが長かったので最初、「???」って感じだったけど、ようやく見えてきた気がする。
で、PythonとC#と混ぜて書いていると書き方が混ざってよく間違う。
なので、両方で同じことをやってみるミニマムコード作って覚書を作ってみた。

どういう人向け?

やっていることはかなり単純なことなので初心者向け。
つまり自分向け。。。

方針

1文字レベルの細かなリテラルが分かればいいかな、と。
で、存在している関数を書く場合と、lambda式をその場で作る場合の2通りを。
まあ、動作確認しやすい四則演算で。
なので、{ 存在している関数, lambda式 } × { +, -, *, / } で8つの関数をlistに束ねてforeachでくるくるする感じで。

出来上がり

コード書式の覚書でしかないのでいきなりコードで。

//c#

using System;
using System.Collections.Generic;

public class Test
{
    public static void Main(string[] args)
    {
        var list = GetFunctionList();
        Export(list, 24, 4);
    }

    //関数定義
    public static List<Func<int, int, int>> GetFunctionList()
    {
        var list = new List<Func<int, int ,int>>();
        list.Add(GetAnsPlus);
        list.Add(GetAnsMinus);
        list.Add(GetAnsMultiple);
        list.Add(GetAnsDivide);
        //list.Add((int x, int y) => x + y);
        //list.Add((int x, int y) => x - y);
        //list.Add((int x, int y) => x * y);
        //list.Add((int x, int y) => x / y);
        list.Add((x, y) => x + y);
        list.Add((x, y) => x - y);
        list.Add((x, y) => x * y);
        list.Add((x, y) => x / y);
        return list;
    }

    //出力
    public static void Export(List<Func<int, int, int>> list, int x, int y)
    {
        foreach (var f in list)
        {
            Console.WriteLine(f(x, y));
        }
    }

    public static int GetAnsPlus(int x, int y) { return x + y; }
    public static int GetAnsMinus(int x, int y) { return x - y; }
    public static int GetAnsMultiple(int x, int y) { return x * y; }
    public static int GetAnsDivide(int x, int y) { return x / y; }

}
■ 出力
C:\projects\qiita\draft\29>29-01.exe
28
20
96
6
28
20
96
6

#Python

def GetAnsPlus(x, y):
    return x + y
def GetAnsMinus(x, y):
    return x - y
def GetAnsMultiple(x, y):
    return x * y
def GetAnsDivide(x, y):
    return x / y

list = []
list.append(GetAnsPlus)
list.append(GetAnsMinus)
list.append(GetAnsMultiple)
list.append(GetAnsDivide)
list.append(lambda x, y: x + y)
list.append(lambda x, y: x - y)
list.append(lambda x, y: x * y)
list.append(lambda x, y: x / y)

for f in list:
    print(f(24, 4))

(base) C:\projects\qiita\draft\29>python 29-02.py
28
20
96
6.0
28
20
96
6.0

感想

うん、まあ、満足。
これ、忘れたころに自分で見に来ることになりそう。
いや、よく、C#とPythonのコードルールをまぜこぜで書こうとしてエラーが出て手が止まったりしてたので。

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1