美文网首页
Haskell 99 Problems

Haskell 99 Problems

作者: 梵_尘 | 来源:发表于2017-04-07 15:47 被阅读47次

H-99: Ninety-Nine Haskell Problems 2017-4-7

首先附上地址: 99 questions/1 to 10 - HaskellWiki

说明:问题的答案只代表我自己的思路,如果你有更好的解决方法,请告诉我。

Problem 1

序列最后一个元素 Ex: [1,2,3,4] -> 4

myLast :: [a] -> a
myLast []     = error "Empty List"
myLast [x]    = x
myLast (_:xs) = myLast xs 

Problem 2

序列倒数第二个元素 Ex: [1,2,3,4] -> 3

myButLast :: [a] -> a
myButLast []     = error "Empty List"
myButLast [x]    = error "Only One Element"
myButLast [x,_]  = x
myButLast (_:xs) = myButLast xs

Problem 3

序列的第k个元素 Ex: elementAt [1,2,3] 2 -> 2

elementAt :: [a] -> Int -> a
elementAt xs n = xs !! (n-1)

Problem 4

序列的长度 Ex: [1,2,3,4] -> 4

myLength :: [a] -> Int
myLength []     = 0
myLength (_:xs) = 1 + myLength xs

Problem 5

反转序列 Ex: [1,2,3] -> [3,2,1]

myReverse :: [a] -> [a]
myReverse []     = []
myReverse (x:xs) = (reverse xs) ++ [x]

Problem 6

判断是否是一个回文序列 Ex: isPalindrome [1,2,3] -> False; isPalindrome "madamimadam" -> True; isPalindrome [1,2,4,8,16,8,4,2,1] -> True

isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome xs = if (length xs) `mod` 2 == 0
                  then False
                  else xs == reverse xs

相关文章

  • Haskell 99 Problems

    H-99: Ninety-Nine Haskell Problems 2017-4-7 首先附上地址: 99 ...

  • 函数式的宗教-00: 认识lisp(clojure)与haske

    总体大纲: lisp与haskell简单介绍 lisp与haskell应用领域 lisp与haskell技术分析 ...

  • monad以及monad的四条定理

    haskell的范畴是hask范畴(haskell的所有类型隶属于hask范畴),所以haskell的所有函子都是...

  • 99. 恢复二叉搜索树

    99. 恢复二叉搜索树[https://leetcode.cn/problems/recover-binary-s...

  • 01 数据类型

    swift中结构体在haskell中的描述 枚举类型在haskell中的描述 枚举携带类型在haskell中描述 ...

  • problems

    WebSocket、HTML、WebGL、客户端数据库 https://threejs.org http://ww...

  • problems

    ∮昨天演讲比赛结果出来了,不出所料。也许是准备不够充分的锅吧,或许也是思想不够深刻?被嘉宾学姐点名表扬的人,说真我...

  • Problems

    zsh报corrupt history file /home/ccsexyz/.zsh_history暴力删除之

  • problems

    i know there are so many problems in our life and anyone ...

  • problems

    1、 2、 3、 4、editding or delete address not working 5、tabba...

网友评论

      本文标题:Haskell 99 Problems

      本文链接:https://www.haomeiwen.com/subject/ufmhattx.html