码迷,mamicode.com
首页 > 其他好文 > 详细

蛤斯凯尔耐听耐

时间:2016-04-13 20:25:39      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

-- Problem 1
-- (*) Find the last element of a list.

-- (Note that the Lisp transcription of this problem is incorrect.)

-- Example in Haskell:

-- Prelude> myLast [1,2,3,4]
-- 4
-- Prelude> myLast [‘x‘,‘y‘,‘z‘]
-- ‘z‘
module Main where
main::IO()
main = putStrLn "Hello World"

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

myLast‘ :: [a] -> a
myLast‘ = head.reverse

myLast‘‘ :: [a] -> a
myLast‘‘ xs = xs!! (length xs -1)

-- 2 Problem 2
-- (*) Find the last but one element of a list.

-- (Note that the Lisp transcription of this problem is incorrect.)

-- Example in Haskell:

-- Prelude> myButLast [1,2,3,4]
-- 3
-- Prelude> myButLast [‘a‘..‘z‘]
-- ‘y‘

myButLast::[a] -> a
myButLast [] = error "error"
myButLast [x] = error "error"
myButLast (x:xs) = 
    if length xs == 1 then x 
    else myButLast xs

myButLast‘ :: [a]->a
myButLast‘ = last.init

myButLast‘‘ ::[a]->a
myButLast‘‘ [x,_] = x
myButLast‘‘ (_:xs) = myButLast‘‘ xs

-- 3 Problem 3
-- (*) Find the K‘th element of a list. The first element in the list is number 1.

-- Example:

-- * (element-at ‘(a b c d e) 3)
-- c
-- Example in Haskell:

-- Prelude> elementAt [1,2,3] 2
-- 2
-- Prelude> elementAt "haskell" 5
-- ‘e‘
    
elementAt :: [a]->Int->a
elementAt (x:_) 1 = x
elementAt (_:xs) n = elementAt xs (n-1)
elementAt _ _ = error "error"

elementAt‘ :: [a]->Int->a
elementAt‘ (x:_) 1 = x
elementAt‘ [] _ = error "error"
elementAt‘ (_:xs) n = 
    if n<1 then error "error" 
    else elementAt‘ xs (n-1)


-- 4 Problem 4
-- (*) Find the number of elements of a list.

-- Example in Haskell:

-- Prelude> myLength [123, 456, 789]
-- 3
-- Prelude> myLength "Hello, world!"
-- 13

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

myLength‘ :: [a] -> Int
myLength‘ = sum . map (\_->1)

-- 5 Problem 5
-- (*) Reverse a list.

-- Example in Haskell:

-- Prelude> myReverse "A man, a plan, a canal, panama!"
-- "!amanap ,lanac a ,nalp a ,nam A"
-- Prelude> myReverse [1,2,3,4]
-- [4,3,2,1]
myReverse :: [a]->[a]
myReverse [] = []
myReverse (x:xs) = myReverse xs ++ [x]

 

蛤斯凯尔耐听耐

标签:

原文地址:http://www.cnblogs.com/ycy1025/p/5388323.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!