欢迎访问宙启技术站
智能推送

Haskell中的

发布时间:2023-12-10 07:04:16

Haskell是一种纯函数式编程语言,它以数学函数为基础,使用不可变数据和 的函数来进行编程。下面是一些Haskell中常用的功能和用法的例子:

1. 定义变量和函数:

x :: Int
x = 42

add :: Int -> Int -> Int
add a b = a + b

2. 列表操作:

list :: [Int]
list = [1, 2, 3, 4, 5]

sumList :: [Int] -> Int
sumList xs = foldl (+) 0 xs
-- 输出: 15

3. 条件判断:

isEven :: Int -> Bool
isEven n = if n mod 2 == 0 then True else False
-- 输出: True

factorial :: Int -> Int
factorial n = if n == 0 then 1 else n * factorial (n - 1)
-- 输出: 120

4. 模式匹配:

length' :: [a] -> Int
length' [] = 0
length' (x:xs) = 1 + length' xs
-- 输出: 5

fibonacci :: Int -> Int
fibonacci 0 = 0
fibonacci 1 = 1
fibonacci n = fibonacci (n - 1) + fibonacci (n - 2)
-- 输出: 55

5. 高阶函数:

map' :: (a -> b) -> [a] -> [b]
map' _ [] = []
map' f (x:xs) = f x : map' f xs

doubleList :: [Int] -> [Int]
doubleList = map (* 2)
-- 输出: [2, 4, 6, 8, 10]

6. 函数组合:

addOne :: Int -> Int
addOne x = x + 1

square :: Int -> Int
square x = x * x

addOneThenSquare :: Int -> Int
addOneThenSquare = square . addOne
-- 输出: 36

7. 嵌套函数:

powerOf2 :: Int -> Int
powerOf2 n = power n 0
  where power 0 acc = acc
        power n acc = power (n - 1) (2 * acc)

-- 输出: 64

8. 惰性求值:

nats :: [Int]
nats = [1..]

take10 :: [Int] -> [Int]
take10 xs = take 10 xs
-- 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

以上只是Haskell的一些基本功能和用法的例子。Haskell还有其他许多特性,如类型类、类型推导、模块系统等,以及许多库和工具可以扩展语言的功能。Haskell的函数式编程范式和强大的类型系统使其成为编写高性能、模块化和可靠的软件的有力工具。