Skip to content

Instantly share code, notes, and snippets.

@kiwipom
Last active December 24, 2015 09:18
Show Gist options
  • Save kiwipom/6775842 to your computer and use it in GitHub Desktop.
Save kiwipom/6775842 to your computer and use it in GitHub Desktop.
Adding numbers without using operators in haskell
-- Based on the c implementation, as per: http://stackoverflow.com/a/365544
import Data.Bits
add' :: (Bits a) => a -> a -> a
add' a b
| a == 0 = b
| otherwise = add' ((a .&. b) `shiftL` 1) (a `xor` b)
> add' 17 13
30
@nzgeek
Copy link

nzgeek commented Oct 14, 2013

Here's a version written in x86 assembler, with a C++ wrapper.

#include <iostream>

void add()
{
    int num1, num2, result;

    std::cout << "Enter an integer: ";
    std::cin >> num1;
    std::cout << "Enter another integer: ";
    std::cin >> num2;

    __asm
    {
        MOV     eax, num1
        MOV     ebx, num2
        CMP     ebx, 0
        JZ      add_done
        add_loop:
        MOV     ecx, eax
        XOR     eax, ebx
        AND     ebx, ecx
        SHL     ebx, 1
        CMP     ebx, 0
        JNZ     add_loop
        add_done:
        MOV     result, eax
    }

    std::cout << num1 << " + " << num2 << " = " << result << std::endl;
}

int main(int argc, char* argv[])
{
    add();

    return 0;
}

It compiles under Visual Studio, but might need some changes to the assembly syntax for other compilers.

@DanielLarsenNZ
Copy link

You guys ROCK

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment