2011-10-02 4 views
5

에 대한 나의 나무는 나는 또한 테스트 트리를 선언하스켈지도는 나무

data Tree a = Leaf a | Node (Tree a) (Tree a) 
     deriving (Show) 

에 의해 정의된다.

myTree = Node (Node (Leaf 1) (Leaf 2)) (Leaf 3) 

내가 원하는 것은 리프에서 작동하는 maptree f 함수를 만드는 것입니다.

다음 maptree f myTree

Node (Node (Leaf 2) (Leaf 3)) (Leaf 4) 

내 솔루션은

maptree f (Leaf a)= Leaf (f a) 
maptree f (Node xl xr) = Node (maptree xl) (maptree xr) 

입니다 반환하지만

Couldn't match expected type `Tree a' 
     against inferred type `Tree t -> Tree t' 
Probable cause: `maptree' is applied to too few arguments 
In the first argument of `Node', namely `(maptree xl)' 
In the expression: Node (maptree xl) (maptree xr) 

실패 다음과 같은 오류를, 모듈로드를 반환합니다, f x = x +1, 더 구체적으로 일하려면 : 없음. 내가

maptree (Leaf a)= Leaf (a + 1) 
maptree (Node xl xr) = Node (maptree xl) (maptree xr) 

을 할 경우

그러나, 운동 않습니다.

첫 번째 기능과 두 번째 기능의 차이점을 볼 수 없습니다. 어떻게 오류가 발생합니까? 감사.

+1

이제 작동하게되었습니다. 나는 바보 야 ...>< –

+0

maptree f (노드 xl xr) = 노드 (maptree xl) 대신 maptree f (노드 xl xr) = 노드 (maptree xl) (maptree xr) –

답변

3

한 벙어리 방법 도우미 사용하면 (고차 함수를 이런 종류의에 대한) 깊은 재귀 적으로 함수를 함께 전달하는 것입니다 잊지하기 : 또는

maptree f (Leaf a)  = Leaf (f a) 
maptree f (Node xl xr) = Node (go xl) (go xr) 
    where go = maptree f 

또는을 (그리고 아마도 더 일반적으로) :

maptree f tree = go tree      -- or eta reduce: maptree f = go 
    where go (Leaf a)  = Leaf (f a) 
      go (Node xl xr) = Node (go xl) (go xr) 

첫 번째 예에서, 나는 maptree f에 대한 매크로로의 go 종류를 사용합니다. 두 번째 예에서는 의 입력 fgomaptreewhere 절에 선언되어 있기 때문에 go 함수 내부의 범위에 있다는 사실을 이용합니다.

8

당신은 재귀 maptree 통화의 기능을 누락 :

maptree f (Leaf a)= Leaf (f a) 
maptree f (Node xl xr) = Node (maptree xl) (maptree xr) 

이 오류 메시지는 기본적으로 무엇이 잘못되었는지를 알 수

maptree f (Leaf a)= Leaf (f a) 
maptree f (Node xl xr) = Node (maptree f xl) (maptree f xr) 
5

해야한다 : 당신은 maptree 충분한 인수를 전달하지 않습니다. maptree f (Node xl xr) 정의는 maptree이 함수와 트리라는 두 개의 인수를 취한다고 말합니다. 그러나 maptree xl과 같이 호출하면 하나의 인수 (트리) 만 나타납니다.

두 번째 버전에서는 maptree을 하나의 인수 (트리) 만 사용하도록 정의했기 때문에 오류가 발생하지 않습니다.

예를 들어 maptree xl 대신 maptree f xl을 호출하여 문제를 해결할 수 있습니다.

8

귀하의 Tree 유형에 대해 Functor 인스턴스의 명백한 fmap입니다. 따라서 DeriveFunctor 확장 프로그램을 사용하여 GHC에서 생성 할 수 있습니다.

{-# LANGUAGE DeriveFunctor #-} 
data Tree a = Leaf a | Node (Tree a) (Tree a) 
    deriving (Functor, Show) 

시도해 보겠습니다.

*Main> fmap (+1) (Node (Node (Leaf 1) (Leaf 2)) (Leaf 3)) 
Node (Node (Leaf 2) (Leaf 3)) (Leaf 4)