javascript 函数JavaScrit与Haskell进行了比较

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 函数JavaScrit与Haskell进行了比较相关的知识,希望对你有一定的参考价值。


// FizzBuzz program written in a purely functional way, first in Javascript and then in Haskell.
/* Limitations in Javascript when implementing pure functional programming :
No loops
No ifs 
Function is a single return (its body is empty)
No side-effects (no interactions with the user)
No assignments in functions
No arrays ??
Only functions with 0 or 1 arguments
*/ 

/********************** Example of a pure function ---> use recursion instead of ifs *******************/
function sum(i) {
    return i <= 0 ? 0: i + sum(i -1);
}

console.log('Suma: ' + sum(5))
/****************** After the video "Haskell for JavaScript programmers" ******************/
////////////////////////////// https://www.youtube.com/watch?v=pUN3algpvMs

let pair = (first) => (second) => {
	return {
		first: first,
		second: second
	};
};

let fst = (p) => p.first
let snd = (p) => p.second

console.log(snd (pair (10) (20)))
let xs = pair (3) (pair (2) (pair (1) (null)))
let head = fst   // It's an alias
let tail = snd   // It's an alias

// console.log(xs)
// console.log(head(xs))
// console.log(tail(xs))

/*
Non-pure function, bridge between the functional and the imperative worlds.
It takes a functional list.
*/
function list2array(xs) {
    let result = [];

    while (xs != null) {
        result.push(head(xs));
        xs = tail(xs);
    }
    return result;
}
/*************************************************************************/

let range = (low) => (high) =>
	low > high 
    ? null 
    : pair (low) (range (low + 1) (high))

    let sequence = list2array(range (1) (100))
	// console.log(sequence);

let map = (f) => (xs) =>
    xs === null 
    ? null
    : pair (f (head (xs))) (map (f) (tail (xs)));

let fizzbuzz = (n) =>
    ((n % 3 === 0 ? 'fizz' : '') + (n % 5 === 0 ? 'buzz' : '') || n)     

// console.log(list2array( map (fizzbuzz) (range (1) (100))) )

/*******************************************************************/
/************************ In Haskell *******************************/
/*******************************************************************/
/*
fizzbuzz n 
    | n `mod` 15 == 0 = "FizzBuzz"
    | n `mod` 3 == 0 = "Fizz"
    | n `mod` 5 == 0 = "Buzz"
    | otherwise = show n

map fizzbuzz [1 .. 100]   
*/

以上是关于javascript 函数JavaScrit与Haskell进行了比较的主要内容,如果未能解决你的问题,请参考以下文章

javascrit--常用互动方法

JavaScrit构造函数原型对象作用意义

javascrit中“字符串为什么可以调用成员”

javascrit开发的基本代码结构的

Javascrit 总结

使用CefSharp在.Net程序中嵌入Chrome浏览器——Javascript交互